Split a string using a string delimiter in C#
This post will discuss how to split a string by a string delimiter in C#.
1. Using String.Split() method
The String.Split() method splits a string into substrings based on the strings in an array.
The following code example demonstrates how to use the String.Split() method to split a string using a string separator with StringSplitOptions.None to include empty array elements in the returned array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
using System; public static class Extensions { public static string[] Split(this string str, string separator) { return str.Split(new string[] { separator }, StringSplitOptions.None); } } public class Example { public static void Main() { string str = "Split##Me##Apart"; string separator = "##"; string[] tokens = str.Split(separator); Console.WriteLine(String.Join(Environment.NewLine, tokens)); } } /* Output: Split Me Apart */ |
2. Using Regex.Split() method
The Regex.Split() method is used to split an input string into an array of substrings at the positions defined by a regular expression match.
The following code example demonstrates how to use the Regex.Split() method to split a string using a string separator.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Text.RegularExpressions; public static class Extensions { public static string[] Split(this string str, string separator) { return Regex.Split(str, separator); } } public class Example { public static void Main() { string str = "Split##Me##Apart"; string separator = "##"; string[] tokens = str.Split(separator); Console.WriteLine(String.Join(Environment.NewLine, tokens)); } } /* Output: Split Me Apart */ |
That’s all about splitting a string using a string delimiter 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 :)