6

Lets say I have

string str = @"Line 1
Line 2
Line 3";

How can I turn this into an array where the 3 elements are "Line 1", "Line 2" and "Line 3".

KangarooChief
  • 381
  • 3
  • 14

2 Answers2

8

use this , The RemoveEmptyEntries option will remove empty lines from the text.

string[] splitted = str.Split(new string[] {System.Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
Ankit
  • 5,733
  • 2
  • 22
  • 23
0

var strArray = str.Split(new [] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

J. D.
  • 1,351
  • 8
  • 13
  • That's going to result in blank strings between the `\r` and `\n` characters. – juharr Aug 18 '17 at 14:06
  • @juharr. Fair enough. Edited to remove empty items. – J. D. Aug 18 '17 at 14:09
  • Note that you now only split on the `\r\n` combination where as before you were splitting if there was only a single `\r` or a single `\n`. This would now remove blank lines which may or may not be desirable. – juharr Aug 18 '17 at 14:11
  • Based on his requirement (that the desired output based on the sample input is three lines), this should suffice. Maybe you should propose an alternate solution...? – J. D. Aug 18 '17 at 14:15
  • No need since this is a clear duplicate. – juharr Aug 18 '17 at 14:16