Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Split() - Method


Split() Method


The Split() Method is used to split a string based on the value provided.


Example :



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);  
   	    }
    }
}


Output :



  Hello
  Beautiful
  World

So, in the above code, we have a String Hello Beautiful World initialised to a variable x.

C_Sharp

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.

C_Sharp

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.


'Split()' Method using separator as an argument


Example :



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);  
   	    }
    }
}


Output :



  Hello
  Beautiful
  World

So, in the above code, we have a String Hello@Beautiful@World initialised to a variable x.

C_Sharp

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.

C_Sharp