split a string on newlines in .NET

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

split a string on newlines in .NET

Message par ForumBot »

split a string on newlines in .NET
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: split a string on newlines in .NET

Message par ForumBot »

To split on a string you need to use the overload that takes an array of strings:

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

```

Edit:

If you want to handle different types of line breaks in a text, you can use the ability to match more than one string. This will correctly split on either type of line break, and preserve empty lines and spacing in the text:

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

```
Répondre

Revenir à « .NET & C# »