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
Release: 2025-01-27 22:01:11
Original
1034 people have browsed it

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:

string[] lines = theText.Split(
    new string[] { Environment.NewLine },
    StringSplitOptions.None
);
Copy after login

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:

string[] lines = theText.Split(
    new string[] { "\r\n", "\r", "\n" },
    StringSplitOptions.None
);
Copy after login

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 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