This post will discuss how to split a string on newlines in C#.

1. Using String.Split() method

The standard way to split a string in C# is using the String.Split() method. It splits a string into substrings and returns a string array. We can optionally pass the StringSplitOptions enum to the Split() method to specify whether include the empty substrings or not. The splitting can be done in two ways:

1. Split by Environment.NewLine

The idea is to split the string using Environment.NewLine, which gets the newline string defined for the current environment.

Download  Run Code

2. Split by Unicode character array

Another way to split the string is using a Unicode character array. To split the string by line break, the character array should contain the CR and LF characters, i.e., carriage return \r and line feed \n.

Download  Run Code

2. Using Regex.Split() method

Alternatively, we can split a string using a regular expression. The idea is to use the Environment.NewLine as a regular expression pattern.

This can be done using the Regex.Split() method, which takes a string to split and a regular expression pattern. Here’s what the code would look like:

Download  Run Code

That’s all about splitting a string on newlines in C#.