Unity杂文——String按行删除

  1. 问题
  2. 解决方案

原文地址

问题

笔者在项目开发过程中需要做一个聊天的假数据显示,是用于demo的,于是笔者就直接用string字符串来模拟显示的数据,但是当聊天内容过多的时候就需要删除历史的聊天内容,于是笔者就想按照行数删除字符串,发现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函数对开始和结束的索引进行删除。


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 841774407@qq.com

×

喜欢就点赞,疼爱就打赏