String Split Utility

By | July 17, 2011

Note: Split function has more no of overload method but the below two I found useful. You may found other overloads helpful in your code.

In this post I am going to discuss about two important thing about Split function of String class. Split function of the string class split the string in array of string.

Split function to split string in array
String.Split( char[])
For example

string words = "stringa,stringb, ,stringc,stringd stringe.";
string [] split = words.Split(new Char [] {' ', ','});

Above code create a string array which has


but What If I want to remove empty string from the array when I split string.
Solution to this problem is to make use of second overload method of the the string Split where you can specify the option to remove string. So above code is rewritten as

Overload method with option
String.Split(Char[], StringSplitOptions)

string words = "stringa,stringb, ,stringc,stringd stringe.";
string [] split = words.Split(new Char [] {' ', ','},StringSplitOptions.RemoveEmptyEntries);

Created string array is


Now consider case where I have to limit no of return string. Consider for example

string a = "key:mykey, Value : test1,test2";

Now I have to get the key:mykey in string 1 and Value : test1,test2 in string 2.
Overload function to split string in limited no. of string
Split(Char[], Int32)
So the code for this is

string a = "key:mykey, Value : test1,test2";
string [] split = words.Split(new Char [] {','},2);

Now the split array have

split[0]= "key:mykey";
split[1]= "Value : test1,test2";

There are also other variable of Split method which you can refer form the msdn link :String.Split. But I fond above two more useful than others.

Author: Pranay Rana

Pranay is MVB on DZone and working as a Senior Software engineer. Doing Web development using Asp.Net ,C#, MS sql server, JQuery/Javascript that he had experience of 4.3 years now. For himdef. of programming is : Programming is something that you do once and that get used by multiple for many years You can visit him on his blog - Follow on twitter : @pranayamr