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".

4
  • 3
    Maybe String.Split can help you? Commented Aug 18, 2017 at 14:04
  • Parse the string, look for line breaks and put them in array. Commented Aug 18, 2017 at 14:04
  • you can simply traverse this string and create a word till you face any '\n' char. By this you can have a word array. Commented Aug 18, 2017 at 14:04
  • var lines = new System.Windows.Forms.TextBox { Text = str }.Lines; Commented Aug 18, 2017 at 14:09

2 Answers 2

9

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

string[] splitted = str.Split(new string[] {System.Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
Sign up to request clarification or add additional context in comments.

Comments

0

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

5 Comments

That's going to result in blank strings between the \r and \n characters.
@juharr. Fair enough. Edited to remove empty items.
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.
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...?
No need since this is a clear duplicate.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.