How to split a string in C#
Dec 01, 2020 09:31 0 Comments C# (C-Sharp) PARTH

                                    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 –

  1. 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.
  2. Split(Char[], Int32, StringSplitOptions) - Splits a string into a maximum number of substrings based on the characters in an array.
  3. 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.
  4. Split(Char[]) - Splits a string into substrings that are based on the characters in an array.
  5. 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.
  6. 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

 

Prev Next
About the Author
Topic Replies (0)
Leave a Reply
Guest User

You might also like

Not sure what course is right for you?

Choose the right course for you.
Get the help of our experts and find a course that best suits your needs.


Let`s Connect