Split string based on newline character in .NET
Splitting a string into separate lines based on newline characters is a very common task in programming. However, using the standard String.Split method with a single delimiter is not always sufficient for this purpose. In .NET, there are two ways to efficiently split a string based on newlines.
Split based on newlines
To split based on a specific newline character (e.g. Environment.NewLine), you can use the String.Split overloaded method with an array of delimiters. This allows you to specify multiple delimiters, including newlines. For example:
string[] lines = theText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
This code will split the input string into an array of lines, where each line is separated by the Environment.NewLine delimiter.
Split based on multiple line break types
In some cases, you may encounter text containing different line breaks, such as "rn", "r" and "n". To handle this situation, you can use multiple separators in the String.Split method. This ensures that all types of newlines are recognized for splitting:
string[] lines = theText.Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
By using this method, the input text will be correctly split into any combination of these newline formats, allowing you to accurately handle multi-line text.
The above is the detailed content of How to Efficiently Split a String into Lines in .NET?. For more information, please follow other related articles on the PHP Chinese website!