Zop*_*iel 1 c# string newline indexof splice
我正在构建一个需要处理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]);
}
}
Run Code Online (Sandbox Code Playgroud)
我想我会使用Split并将结果添加到数组中,但我似乎无法使其正常工作.
更好的方法可能是按空格分割并重建短于30个字符的数组行.
以下是我将如何做到这一点(未经测试):
string[] words = myString.Split(' ');
StringBuilder sb = new StringBuilder();
int currLength = 0;
foreach(string word in words)
{
if(currLength + word.Length + 1 < 30) // +1 accounts for adding a space
{
sb.AppendFormat(" {0}", word);
currLength = (sb.Length % 30);
}
else
{
sb.AppendFormat("{0}{1}", Environment.NewLine, word);
currLength = 0;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1410 次 |
| 最近记录: |