How to split a string in C#
How to split a string in C#
We use the Split method to split a string into an array of strings separated by a delimiter. The split delimiters can be a character or an array of characters or an array of strings.
The String.Split() method has various forms –
- Split(String[], Int32, StringSplitOptions) - Splits a string into a maximum number of substrings based on the strings in an array. You can specify whether the substrings include empty array elements.
- Split(Char[], Int32, StringSplitOptions) - Splits a string into a maximum number of substrings based on the characters in an array.
- Split(String[], StringSplitOptions) - Splits a string into substrings based on the strings in an array. You can specify whether the substrings include empty array elements.
- Split(Char[]) - Splits a string into substrings that are based on the characters in an array.
- Split(Char[], StringSplitOptions) - Splits a string into substrings based on the characters in an array. You can specify whether the substrings include empty array elements.
- Split(Char[], Int32) - Splits a string into a maximum number of substrings based on the characters in an array. You also specify the maximum number of substrings to return.
Let’s see an example of splitting a string into an array of string which are separated by comma –
string fruits = "Apple, Banana, Mango, Orange, Watermelon";
string[] listOfFruits = fruits.Split(", ");
foreach (string fruit in listOfFruits )
{
Console.WriteLine(fruit);
}
Output – Apple
Banana
Mango
Orange
Watermelon
Let’s see another example of splitting a string into an array of string which are separated by multiple delimiters (comma, fullstop, blank) –
string fruits = "Apple, Banana. Mango, Orange. Watermelon";
string[] listOfFruits = fruits.Split(new Char [] {' ', ',', '.'} );
foreach (string fruit in listOfFruits )
{
if(fruit.Trim() != “”)
{
Console.WriteLine(fruit);
}
}
Output – Apple
Banana
Mango
Orange
Watermelon
Let’s see one final example of splitting a string into an array of string which are delimited by a string or an array of strings -
string fruits = "Apple, Banana, Mango, Orange, Watermelon";
string[] stringOfSeparators = new string[] { "Mango, ", "Orange, " };
string[] listOfFruits = fruits.Split(stringOfSeparators, StringSplitOptions.None );
foreach (string fruit in listOfFruits )
{
Console.WriteLine(fruit);
}
Output – Apple, Banana,
Watermelon
