example:
string str = "Lorem ipsum dolor sit amet,
consetetur sadipscing elitr, sed diam nonumy eirmod tempor
invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.";
string firstline;
How can I get just the first line from the string "str" into the string "firstline"?
Use the readline() Function to Read the First Line of File in Python. Another method to read the first line of a file is using the readline() function that reads one line from the stream.
.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();
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));
Assuming your string really contains new lines (\r
and \n
), you can use:
string line1 = str.Split(new [] { '\r', '\n' }).FirstOrDefault()
String.Split
will create a whole array of substrings, which is wasteful for your requirement. I would suggest using an index-based approach:
int index = str.IndexOfAny(new char[] { '\r', '\n' });
string firstline = index == -1 ? str : str.Substring(0, index);
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