Split a string on whitespace characters in C#
This article illustrates the different techniques to split a string on the whitespace characters in C#.
The standard solution to split a string on the given characters is using the String.Split() method. If no delimiter is specified, it splits the string on whitespace characters. Here’s an example of its usage:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { String s = "Split by\twhitespace"; string[] tokens = s.Split(); Console.WriteLine(String.Join(", ", tokens)); // Split, by, whitespace } } |
To handle multiple spaces, you can use the String.Split(char[]) method overload with StringSplitOptions.RemoveEmptyEntries option, as shown below.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { String s = "Split by\t\twhitespace"; string[] tokens = s.Split(new char[0], StringSplitOptions.RemoveEmptyEntries); Console.WriteLine(String.Join(", ", tokens)); // Split, by, whitespace } } |
The above solution creates a new object. To avoid creating a new object, you can use (char[]) null instead of new char[0].
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { String s = "Split by\t\twhitespace"; string[] tokens = s.Split((char[]) null, StringSplitOptions.RemoveEmptyEntries); Console.WriteLine(String.Join(", ", tokens)); // Split, by, whitespace } } |
You can also create an extension function to split a string on whitespace. To split the string only on some whitespace characters, you can pass them in the char array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; public static class StringExtensions { public static string[] SplitOnWhitespace(this string input) { char[] whitespace = new char[] { ' ', '\t', '\r', '\n' }; return input.Split(whitespace, StringSplitOptions.RemoveEmptyEntries); } } public class Example { public static void Main() { String s = "Split by\twhitespace"; string[] tokens = s.SplitOnWhitespace(); Console.WriteLine(String.Join(", ", tokens)); // Split, by, whitespace } } |
That’s all about splitting a string on the whitespace characters 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 :)