C# 编辑字符串以添加特定长度的换行符
我正在构建一个需要处理 Twitter 消息的应用程序。我需要一个将字符串切割为 30 个字符的功能,如果第 30 个索引处的字符不是空格,它将向后计数,直到找到空格并向其添加 \n,以便它显示为多行在我的应用程序中。
我尝试了多种方法,但我对 C# 的了解还不是那么令人惊叹。我得到了一些基本的东西。
string[] stringParts = new string[5];
string temp = jsonData["results"][i]["text"].ToString();
int length = 30;
for(int count = length-1; count >= 0; count--)
{
if(temp[count].Equals(" "))
{
Debug.Log(temp[count]);
}
}
我想我应该使用 Split 并将结果添加到数组中,但我似乎无法让它工作。
I'm building an application that needs to deal with twitter messages. I have need of a functionality that cuts a string up at 30 characters, if the character at the 30 index isn't a space it will count back till it finds a space and add a \n to it so that it displays as multi line in my application.
I've tried several approaches but my knowledge of C# isn't that amazing yet. I got something basic going.
string[] stringParts = new string[5];
string temp = jsonData["results"][i]["text"].ToString();
int length = 30;
for(int count = length-1; count >= 0; count--)
{
if(temp[count].Equals(" "))
{
Debug.Log(temp[count]);
}
}
I figured i'd use Split and add the result to an array, but i can't seem to get it working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更好的方法可能是用空格分割并重建少于 30 个字符的数组行。
以下是我将如何执行此操作的概述(未经测试):
A better approach may be to split by spaces and reconstruct for the array lines that are shorter than 30 characters.
Here is an outline of how I would do this (untested):
我将使用正则表达式来确定空白块的最后位置,以及后面的第一个非空白字符的位置。
I would use regular expressions to determine the last position of whitespace block, as well as the position of first non-whitespace character that follows.
感谢奥德的回答。
我从 Oded 答案开始,然后将其变成可重用的函数。
这是我对该功能的单元测试。
Thanks Oded for your answer.
I started with Oded answer and then made it into a reusable functions.
Here is my unit test for the function.