The Split() Method is used to split a string based on the value provided.
public class MyApplication
{
public static void Main(string[] args)
{
string x = "Hello Beautiful World";
string[] str = x.Split(' ');
foreach (var s in str) {
System.Console.WriteLine(s);
}
}
}
So, in the above code, we have a String Hello Beautiful World initialised to a variable x.
-Method1.png)
Then we have used the split() function on the variable x.
string[] str = x.Split(' ');So, the Split() function converts the String, Hello Beautiful World to an Array, separated by a space (i.e. ' ').
And initialises the array to the variable str.
-Method2.png)
So, if you see the above String, Hello Beautiful World.
Hello, Beautiful and World are separated by a space (i.e. ' ').
So, an array is formed with Hello, Beautiful and World.
But what if the Strings are separated by @ or any other symbol.
Say, the below String is separated by @.
"Hello@Beautiful@World"
Now, if you want to form an array with Hello, Beautiful and World. You can use Split() function providing the separator @ as argument.
public class MyApplication
{
public static void Main(string[] args)
{
string x = "Hello@Beautiful@World";
string[] str = x.Split('@');
foreach (var s in str) {
System.Console.WriteLine(s);
}
}
}
So, in the above code, we have a String Hello@Beautiful@World initialised to a variable x.
-Method3.png)
Then we have used the Split() function with the separator @ as argument on the variable x.
string[] str = x.Split('@');So, the Split() function converts the String, Hello@Beautiful@World to an Array, separated by the separator (i.e. @).
And initialises the Array to the variable str.
-Method4.png)