How to use the Split() method in C#

Split() in C# programming language is used to split a string into an array of characters or strings.

It returns an array of strings or characters, which we get by splitting the original string separated by the delimiter passed to the Split() method. In other words, where the delimiter is found, a substring is made an element of an array.

Syntax

string.Split(ch)

Parameters

ch: This is the character or delimiter by which to split characters or strings in the original string.

Return value

An array of strings or characters is returned.

Code example

In the example below, we will create a string and form an array of from the delimiter specified.

// create your class
class StringSplitter
{
// create main method
static void Main()
{
// create strin
string s1 = "Educative is the best";
// split where there is whitespace
string[] s2 = s1.Split(' ');
// print out elements of the array
foreach (string elem in s2){
// print element one by one
System.Console.WriteLine(elem);
}
}
}

In the code above, the string s1 was split to become an array of strings. The Split() method took white-space ' ' as its parameter. So, anywhere the s1 has white-space, that is where it should split.

Finally, we looped through the returned array, and printed out its elements.

Free Resources