Split a string on newlines in C#
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; public class Example { public static void Main() { string lines = @"Split This String"; string[] strings = lines.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries); Console.WriteLine(String.Join(',', strings)); } } /* Output: Split,This,String */ |
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
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; public class Example { public static void Main() { string lines = @"Split This String"; char[] delims = new[] { '\r', '\n' }; string[] strings = lines.Split(delims, StringSplitOptions.RemoveEmptyEntries); Console.WriteLine(String.Join(',', strings)); } } /* Output: Split,This,String */ |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; using System.Text.RegularExpressions; public class Example { public static void Main() { String lines = @"Split This String"; string[] strings = Regex.Split(lines, Environment.NewLine); Console.WriteLine(String.Join(',', strings)); } } /* Output: Split,This,String */ |
That’s all about splitting a string on newlines in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)