取字符串的最后n行c#

use*_*670 11 c# string string-parsing

我有一串未知的长度

它是格式

\nline
\nline
\nline
Run Code Online (Sandbox Code Playgroud)

知道多长时间我怎么能把字符串的最后10行用"\n"分隔一行

Sim*_*zie 13

随着字符串变大,避免处理无关紧要的字符变得更加重要.使用任何方法string.Split都是低效的,因为必须处理整个字符串.一个有效的解决方案必须从后面穿过字符串.这是一个正则表达式方法.

请注意,它返回a List<string>,因为结果需要在返回之前反转(因此使用该Insert方法)

private static List<string> TakeLastLines(string text, int count)
{
    List<string> lines = new List<string>();
    Match match = Regex.Match(text, "^.*$", RegexOptions.Multiline | RegexOptions.RightToLeft);

    while (match.Success && lines.Count < count)
    {
        lines.Insert(0, match.Value);
        match = match.NextMatch();
    }

    return lines;
}
Run Code Online (Sandbox Code Playgroud)


Vol*_*lma 8

var result = text.Split('\n').Reverse().Take(10).ToArray();
Run Code Online (Sandbox Code Playgroud)

  • +1虽然这会颠倒可能无人看管的线的顺序.你可以在最后添加另一个`Reverse`.`ToArray()`是多余的,因为OP没有提到他想要一个数组. (3认同)

Rob*_*vey 6

Split()字符串打开\n,并获取结果数组的最后10个元素.