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
Release: 2025-01-27 21:46:14
Original
733 people have browsed it

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>
Copy after login

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>
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template