In this article, we will cover different ways to split a string in C#.
As developers, we might often need to split strings into smaller substrings based on certain delimiters. C# provides us with the Split method, which is part of the String
class.
There are six different overloaded versions of the Split method, each with its unique set of parameters and functionalities. We’ll be looking into them in this article.
About Stringsplitoptions
We can use the StringSplitOptions
enumeration as a parameter for the Split method in C#. By doing so, we can specify whether to include or exclude empty substrings from the resulting array when splitting a string.
The StringSplitOptions
enumeration has 3 possible values:
- None
- RemoveEmptyEntries
- TrimEntries
If both RemoveEmptyEntries
and TrimEntries
options are used together substrings that contain only whitespaces will also be excluded from the resulting array. This is because TrimEntries
removes any leading or trailing whitespaces from substrings before determining if they are empty, and then RemoveEmptyEntries
removes any empty substrings from the result.
Split a String Based on a Char[]
The Split(Char[]?)
method allows us to split a string into an array of substrings based on a specified array of characters:
class Program { static void Main(string[] args) { string str = "apple,banana,cherry;date"; char[] delimiterChars = { ',', ';'}; string[] words = str.Split(delimiterChars); foreach (string s in words) { Console.WriteLine(s); } } }
In the example, we utilize the Split(Char[])
method to divide a string based on a delimiter array of characters.
Here’s the output of the program:
apple banana cherry date
Split a String Based on Char[] With Stringsplitoptions
The Split(Char[]?, StringSplitOptions)
method in C# allows us to split a string into an array of substrings based on multiple delimiter characters.
We can use the StringSplitOptions
to specify whether empty entries and/or whitespaces should be removed from the resulting array:
class Program { static void Main(string[] args) { string input = "John & Jane & James"; char[] delimiterChars = { ' ', '&' }; string[] words = input.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries); foreach (string word in words) { Console.WriteLine(word); } } }
In this example, we use StringSplitOptions.RemoveEmptyEntries
to remove any empty entries from the resulting string array.
Finally, after we run our app, we can inspect the result:
John Jane James
Extract Maximum Number of Substrings Based on the Char[]
The Split(Char[]?, Int32)
method in C# is another overloaded version of the Split method that allows us to split a string into substrings based on a specified delimiter character array, but with an additional count parameter that limits the number of substrings returned.
Let’s take a look at an example of how we can use this overloaded method in our code:
class Program { static void Main(string[] args) { string input = "apple,banana,cherry,orange"; char[] delimiterChars = { ',' }; string[] fruits = input.Split(delimiterChars, 3); foreach (string fruit in fruits) { Console.WriteLine(fruit); } } }
We use the Split method to split a string into an array of substrings based on an array of delimiter characters. We limit the number of substrings returned to 3 and output each element to the console.
It’s important to keep in mind that if the specified delimiter characters appear more than count times in the input string, the resulting string array will contain count or fewer elements. The final element will contain the remainder of the input string:
apple banana cherry,orange
Split a String Using the Char[] With Options
We use the Split(Char[]?, Int32, StringSplitOptions)
method to split a string into an array of substrings based on multiple delimiter characters.
Additionally, this method includes the option to limit the maximum number of substrings that the resulting array can contain and exclude any empty substrings from the array.
Let’s consider the example of how to apply this method:
class Program { static void Main(string[] args) { string input = " apple , banana ; cherry,orange "; char[] delimiterChars = { ',', ';' }; string[] fruits = input.Split(delimiterChars, 3, StringSplitOptions.TrimEntries); foreach (string fruit in fruits) { Console.WriteLine(fruit); } } }
In this example, we define a string input with extra whitespace and we call the Split method on the input string, passing in the delimiterChars
array and StringSplitOptions.TrimEntries
to remove any leading or trailing whitespace.
When we run the program, we will see the output:
apple banana cherry,orange
When we use the option StringSplitOptions.TrimEntries
, it removes any leading or trailing white spaces from the resulting substrings.
As a result, the first and second substring is printed without any leading or trailing spaces, and the third substring is printed without any leading space before “cherry” and any trailing spaces after “orange”.
Split a String Based on String[] With Options
We use the Split method with String[]
and StringSplitOptions
options to split a string based on an array of string delimiters while specifying the behavior of the method when encountering empty or whitespace elements:
class Program { static void Main(string[] args) { string input = "apple,banana,kiwi;grape,mango,orange"; string[] separators = { ",", ";" }; string[] fruits = input.Split(separators, StringSplitOptions.RemoveEmptyEntries); foreach (string fruit in fruits) { Console.WriteLine(fruit); } } }
In this example, we define a string input with multiple delimiters and an array of separators with a comma and a semicolon. We call the Split
method on the input string with the separators array and the RemoveEmptyEntries
option.
The output of this program would be:
apple banana kiwi grape mango orange
Split a String Using the String[]
In the Split(String[], Int32, StringSplitOptions)
overload, we pass in an array of separator strings and the integer value to limit the number of substrings returned.
We also specify the RemoveEmptyEntries
option to exclude any empty entries or whitespaces from the resulting substrings array.
Now, let’s see how to use this method with an example:
class Program { static void Main(string[] args) { string input = "apple,banana,cherry,orange,pear"; string[] separators = { "," }; string[] fruits = input.Split(separators, 3, StringSplitOptions.RemoveEmptyEntries); foreach (string fruit in fruits) { Console.WriteLine(fruit); } } }
In this example, we split a string input that contains a comma using the Split method with a comma separator, a limit of 3 substrings, and the RemoveEmptyEntries
option.
Here is the output generated by the program when executed:
apple banana cherry,orange,pear
How to Split a String Into New Lines
To split a string into new lines, we can use the Split
method in combination with the Environment.NewLine
property.
This approach allows us to split the string at each occurrence of a newline character sequence, which could be either a single newline or a combination of a carriage return and a newline depending on the platform.
Let’s take a look at an example:
class Program { static void Main(string[] args) { string multiLineText = "Line 1\nLine 2\nLine 3\nLine 4\nLine 5"; string[] lines = multiLineText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); foreach (string line in lines) { Console.WriteLine(line); } } }
We define a multi-line string that contains five lines of text separated by newline characters. We then call the Split method usingEnvironment.NewLine
as the delimiter to split the string at each occurrence of a newline character sequence. The resulting array contains five elements, each representing a single line from the original string:
Line 1 Line 2 Line 3 Line 4 Line 5
Optimizing the Performance of the Split() Method in C#
When we are using the Split method in C#, there are a few performance considerations to keep in mind.
First, the method creates an array to hold the substrings, which can be expensive in terms of memory usage, especially when processing large strings.
Another consideration is the use of StringSplitOptions
enumeration. If the RemoveEmptyEntries
is specified, the method has to perform additional checks to skip over any empty substrings, which can impact performance.
One way we can improve the performance of the Split
method is to use an overload that takes a character delimiter instead of a string. This can be faster since it doesn’t require creating a string object for each delimiter.
Another approach is to use the IndexOf()
method to locate the delimiter characters manually, and then extract the substrings using the Substring()
method. Though this requires more code, it can be faster in some cases, especially if the input string is large.
To learn more about using the IndexOf()
and Substring()
methods in C# strings, check out our informative article on string methods.
Conclusion
Throughout this article, we have gained knowledge about the split string method in C#. We have also discovered the different overloaded methods and learned how to utilize them.