I have a string of unknown length
it is in the format
\nline
\nline
\nline
with out know how long it is how can i just take the last 10 lines of the string a line being separated by "\n"
As the string gets larger, it becomes more important to avoid processing characters that don't matter. Any approach using string.Split
is inefficient, as the whole string will have to be processed. An efficient solution will have to run through the string from the back. Here's a regular expression approach.
Note that it returns a List<string>
, because the results need to be reversed before they're returned (hence the use of the Insert
method)
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;
}
var result = text.Split('\n').Reverse().Take(10).ToArray();
Split()
the string on \n
, and take the last 10 elements of the resulting array.
If this is in a file and the file is particularly large, you may want to do this efficiently. A way to do it is to read the file backwards, and then only take the first 10 lines. You can see an example of using Jon Skeet's MiscUtil library to do this here.
var lines = new ReverseLineReader(filename);
var last = lines.Take(10);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With