Home >Backend Development >C++ >How to Split a String by Newlines in C#?

How to Split a String by Newlines in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-27 22:01:11990browse

How to Split a String by Newlines in C#?

Split string by newline character in C#

The Split method provided by the .NET framework can split a string into separate lines based on newline characters. However, the standard usage of Split requires a character array as the delimiter, so splitting by newline is not suitable.

Solution:

To efficiently split strings in .NET by newlines, you can use the overload of the Split method that accepts an array of strings as delimiters:

<code class="language-csharp">string[] lines = theText.Split(
    new string[] { Environment.NewLine },
    StringSplitOptions.None
);</code>

Here, theText represents the input string, and Environment.NewLine represents the newline character unique to the current operating system. StringSplitOptions.None means that splitting should not consider any spaces or empty elements.

Handles different line break types:

If the input string contains different types of newlines (e.g. CR LF vs. just LF), the following updated code can handle this change:

<code class="language-csharp">string[] lines = theText.Split(
    new string[] { "\r\n", "\r", "\n" },
    StringSplitOptions.None
);</code>

This approach allows for correct segmentation regardless of the newline format used in the text.

The above is the detailed content of How to Split a String by Newlines in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn