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)
var result = text.Split('\n').Reverse().Take(10).ToArray();
Run Code Online (Sandbox Code Playgroud)