问题
在unity开发过程中,如果一个string字符串有多行,如果我们想删除前面一行或者多行应该如何操作?
解决方案
private static string DeleteStrLine(string text, int startLine, int lineCount)
{
var curIndex = 0;
int? remStartIndex = null;
var sum = 1;
while (sum < startLine + lineCount)
{
if (sum == startLine) remStartIndex = curIndex;
curIndex = text.IndexOf("\n", curIndex, StringComparison.Ordinal);
if (curIndex < 0)
{
curIndex = text.Length;
break;
}
curIndex++;
sum++;
}
if (remStartIndex == null)
{
return text;
}
text = text.Remove(remStartIndex.Value, curIndex - remStartIndex.Value);
return text;
}
思路就是通过IndexOf函数遍历找到需要删除的行对应的"\n"(换行)的索引,然后再通过Remove函数对开始和结束的索引进行删除。









网友评论