What is the Split method in C#?

The Split() method is part of the string class in C#. The method is used to split a string based on the delimiters passed to the string.

The delimiters can be a character, an array of characters, or even an array of strings. We can also pass the function an array of strings to be split on the delimiters passed to it.

svg viewer

Code

The following code illustrates the various ways that the split() function can be used. Note the various type of arguments passed to the function.

1. Splitting a string on a character

using System;
class Program
{
static void Main()
{
string sentence = "czechoslovakia";
string[] words = sentence.Split('o');
foreach (string word in words)
{
Console.WriteLine(word);
}
}
}

2. Splitting a string on an array of characters

using System;
class Program
{
static void Main()
{
string sentence = "the quick:brown fox";
char[] separator = { ':', ' ' };
string[] words = sentence.Split(separator);
foreach (string word in words)
{
Console.WriteLine(word);
}
}
}

3. Splitting a string on an array of strings

using System;
class Program
{
static void Main()
{
string[] separator = { "<<", "..." };
string sentence = "one<<two......three<four";
string[] words = sentence.Split(separator, System.StringSplitOptions.RemoveEmptyEntries);
foreach (var word in words)
{
System.Console.WriteLine(word);
}
}
}
Copyright ©2024 Educative, Inc. All rights reserved