C# String Split() Method

www‮figi.‬tidea.com

The Split() method in C# is used to split a string into an array of substrings based on a specified separator or set of separators. The resulting substrings are stored as elements in the array.

The syntax of the Split() method is as follows:

string[] splitArray = string.Split(separator);

or

string[] splitArray = string.Split(separator, count);

Here, separator is the character or set of characters that the string is split on, and count is the maximum number of substrings to return. If count is not specified, all substrings are returned.

For example, to split a string into an array of substrings based on whitespace, you can use the following code:

string text = "The quick brown fox";
string[] words = text.Split(' ');
foreach (string word in words)
{
    Console.WriteLine(word);
}

In this example, the Split() method is used to split the string "The quick brown fox" into an array of substrings based on the whitespace character. The resulting array words contains the substrings "The", "quick", "brown", and "fox", which are printed to the console using a foreach loop.

You can also split a string based on a set of characters, such as a comma-separated list. For example, to split a string into an array of substrings based on commas, you can use the following code:

string text = "apple,banana,orange";
string[] fruits = text.Split(',');
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

In this example, the Split() method is used to split the string "apple,banana,orange" into an array of substrings based on commas. The resulting array fruits contains the substrings "apple", "banana", and "orange", which are printed to the console using a foreach loop.

Note that the Split() method returns an array of strings. If you need to split a string into a list or another type of collection, you will need to convert the array to that type using appropriate methods or constructors.