新手求,处理字符串方法,在线等!
一个字符串长度超过20,现在要在每个20长度的位置加上\n(回车符),如下:
string str= "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ";
使用方法转换成:
str= "aaaaaaaaaaaaaaaaaaaa\naaaaaaaaaaaaaaaaaaaa\naaaaaaaaaaaaaaaaa ";
求些方法,小弟在线等各位指教!
------解决方案--------------------str=str.Insert(20, "\n ");
str=str.Insert(41, "\n ");
以此类推,写个循环
------解决方案--------------------for(int i=20;;i+=20)
{
try
{
str=str.Insert(i, "\n ");
}
catch
{
break;
}
}
------解决方案--------------------StringBuilder sb = new StringBuilder();
int i;
for(i=0;i <str.Length-20;i+=20)
sb.Append(str.Substring(i, 20)).Append( "\n ");
sb.Append(str.Substring(i)).Append( "\n ");
------解决方案--------------------string str = "BaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaE ";
StringBuilder sb = new StringBuilder();
int c = (str.Length - 1) / 20 + 1;
for (int i = 0; i < c; i++)
{
int idx = i * 20;
int l=str.Length-idx;
if (l > 20)
l = 20;
sb.AppendLine(str.Substring(i*20,l));
}
MessageBox.Show(sb.ToString());