Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Split string by lines? [duplicate]

Tags:

c#

Let's say, for example, I have the following string downloaded from a .txt file in the web.

line1
line2
line3

How can I split the whole string by lines, so I can use splitted[0] to get line1, splitted[1] to get line 2, etc..? Thanks!

Can I use?

string[] tokens = Regex.Split(input, @"\r?\n|\r");

Thanks

like image 472
user2714359 Avatar asked Feb 08 '26 04:02

user2714359


1 Answers

Use File.ReadAllLines to get the string[] with all lines:

string[] allLines = File.ReadAllLines(path);
string line10 = allLines[9]; // exception if there are less
string line100 = allLines.ElementAtOrDefault(99); // null if there are less

If you already have a string you can use String.Split with Environment.NewLine

string[] textLines = text.Split(new[]{ Environment.NewLine }, StringSplitOptions.None);
like image 113
Tim Schmelter Avatar answered Feb 12 '26 04:02

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!