Unity杂文——String按行删除

2023-09-29  本文已影响0人  脸白

原文地址

问题

在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函数对开始和结束的索引进行删除。

上一篇 下一篇

猜你喜欢

热点阅读