Splitting a String By Desired Character in C#
In C#, if we want to split a string variable into the character or characters we want, we use the "Split()" method.
Although there are multiple uses of the "split()" method, here we will show the simplest and most used form.
The method returns an array of strings after splitting.
Its usage is as follows.
namespace ConsoleApplicationTest
{
class Program
{
static void Main(string[] args)
{
string cities = "Miami, London, Paris, Berlin, Rome, Madrid";
string[] cityArray = cities.Split(',');
}
}
}
The cityArray array is assigned in the order Miami, London, Paris, Berlin, Rome, Madrid.
You can review the results by adding the code below.
Console.WriteLine(cityArray[0]);
Console.WriteLine(cityArray[1]);
Console.WriteLine(cityArray[2]);
Console.WriteLine(cityArray[3]);
Console.WriteLine(cityArray[4]);
Console.WriteLine(cityArray[5]);
Console.ReadLine();