Home >Backend Development >C++ >How Can I Efficiently Split a String into Lines in .NET?

How Can I Efficiently Split a String into Lines in .NET?

Susan Sarandon
Susan SarandonOriginal
2025-01-27 21:46:14737browse

How Can I Efficiently Split a String into Lines in .NET?

Split string by newline in .NET

Question:

You want to split a string by newline in .NET, but the Split method doesn't seem to be suitable for this task. What's the best way to accomplish this task?

Answer:

To split a string by newlines, use the overload of the Split method with an array of strings:

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

Please note that Environment.NewLine represents a newline character or sequence applicable to the current platform.

Handling different types of line breaks:

If your text may contain different types of line breaks (for example, CRLF and LF), you can handle this by using an array containing multiple string values ​​in the Split method:

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

This will correctly split any type of newline characters, preserving any empty lines or spaces in the text.

The above is the detailed content of How Can I Efficiently Split a String into Lines in .NET?. 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