How can I get only the first line from a string?
Instead of string.Split
I would use string.Substring
and string.IndexOf
to get only the first line and avoid unnecessary string[]
with the entire input string.
string firstline = str.Substring(0, str.IndexOf(Environment.NewLine));
.NET already has a line-reader: StringReader
. This saves worrying about what constitutes a line break, and whether there are any line breaks in the string.
using (var reader = new StringReader(str))
{
string first = reader.ReadLine();
}
The using statement is used for disposing any non-managed resources consumed by the reader
object. When using C#8 it can be simplified like so:
using var reader = new StringReader(str);
string first = reader.ReadLine();
Assuming your string really contains new lines (\r
and \n
), you can use:
string line1 = str.Split(new [] { '\r', '\n' }).FirstOrDefault()