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?
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.
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 .
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.
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.
What about using a StringReader
?
using (System.IO.StringReader reader = new System.IO.StringReader(input)) { string line = reader.ReadLine(); }
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With