Best way to split newline string in .NET
Splitting a string by newline in .NET may seem like a simple task, but just using the Split method is not enough. This article explores the best ways to do this.
To split a string based on newline characters, you need to use an overloaded version of the Split method, which accepts an array of strings as a parameter:
<code class="language-csharp">string[] lines = theText.Split( new string[] { Environment.NewLine }, StringSplitOptions.None );</code>
This code initializes a string array containing only newline characters, matching all occurrences of newline characters in the specified text. By setting StringSplitOptions.None, each newline character will cause a new element to appear in the lines array.
For situations where the text may contain various types of line breaks, including carriage returns and line feeds, a more comprehensive approach is needed:
<code class="language-csharp">string[] lines = theText.Split( new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.None );</code>
This enhanced version ensures recognition of both types of newlines and efficient handling of empty lines and spaces.
The above is the detailed content of How to Efficiently Split a String on Newlines in .NET?. For more information, please follow other related articles on the PHP Chinese website!