C# – How to split a string

String can be split into collection of substrings based on a defined character (separator) using Split() function. Split is part of String class which exists in the System namespace.

Split function is overloaded and has various forms which allow to:

  • pass separator as a single character, array of characters, single string or array of strings;
  • define maximum number of substrings in output array;
  • define split options like removing empty elements from returned collection.

Below you can find examples which present each of above options. Every case has variable named input containing string to be split, variable named output which is array of strings being a result of Split function. Achieved substrings are printed to the console with following code:

Split by a single character

Result:

Split by array of characters

Result:

Split by a single string

Result:

Split by array of strings

There is no form of Split which accepts only one input parameter which would be array of strings. As a result of what we need to pass second parameter which is split options. In below example we use “None”, which behaves the same as previous three examples where we didn’t pass such parameter.

Result:

Split with maximum number of substrings

In below example we limit the number of substrings in the output collection to three. It can be easily done by passing integer parameter on the second place to Split function.

Result:

Split with option to remove empty items from the output

Result:

Without StringSplitOptions.RemoveEmptyEntries or with StringSplitOptions.None the output would look like: