2

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

user2714359
  • 117
  • 1
  • 3
  • 9

3 Answers3

11

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);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Thanks. I have another question. The string I'm getting is 0x0B, for example. When using short.Parse, it fails, it says the input wasn't in correct format. Why's that? If I use 0x0B in VS it works fine, but when I get it from, a text file.. – user2714359 Sep 13 '13 at 08:36
  • Additionally, if the file is large, OP can use [`File.ReadLines`](http://msdn.microsoft.com/en-us/library/dd383503.aspx) which returns an `IEnumerable`, i.e. yields lines one by one. That's useful if there is no need to keep all lines in memory at the same time. – vgru Sep 13 '13 at 08:37
  • @user2714359: You might want to ask another question then. You're welcome :) – Tim Schmelter Sep 13 '13 at 08:46
  • @user2714359: Don't forget to accept the answer which solves your problem. You haven't accepted any answers for your questions so far. – vgru Sep 13 '13 at 08:49
6

Use this:

var result = Regex.Split(text, "\r\n|\r|\n");

as indicated here: Best way to split string into lines

Community
  • 1
  • 1
Alex
  • 5,971
  • 11
  • 42
  • 80
2

If you are downloading a file, then open it and ReadAllLines

var f= File.ReadAllLines(filPath)

ReadAllLines returns string[].

Giannis Paraskevopoulos
  • 18,261
  • 1
  • 49
  • 69