Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to split a string on newlines in .NET?

I need to split a string into newlines in .NET and the only way I know of to split strings is with the Split method. However that will not allow me to (easily) split on a newline, so what is the best way to do it?

like image 933
RCIX Avatar asked Oct 10 '09 09:10

RCIX


People also ask

How can I split a string in C#?

Split(char[]) Method This method is used to splits a string into substrings that are based on the characters in an array. Syntax: public String[] Split(char[] separator); Here, separator is a character array that delimits the substrings in this string, an empty array that contains no delimiters, or null.

How do I split a string into a newline?

Split String at Newline Split a string at a newline character. When the literal \n represents a newline character, convert it to an actual newline using the compose function. Then use splitlines to split the string at the newline character. Create a string in which two lines of text are separated by \n .

How do I split a string into multiple places?

To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.

How do you split a string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


2 Answers

What about using a StringReader?

using (System.IO.StringReader reader = new System.IO.StringReader(input)) {     string line = reader.ReadLine(); } 
like image 40
Clément Avatar answered Oct 07 '22 08:10

Clément


To split on a string you need to use the overload that takes an array of strings:

string[] lines = theText.Split(     new string[] { Environment.NewLine },     StringSplitOptions.None ); 

Edit:
If you want to handle different types of line breaks in a text, you can use the ability to match more than one string. This will correctly split on either type of line break, and preserve empty lines and spacing in the text:

string[] lines = theText.Split(     new string[] { "\r\n", "\r", "\n" },     StringSplitOptions.None ); 
like image 137
Guffa Avatar answered Oct 07 '22 10:10

Guffa