Pranay Rana: String Split Utility

Sunday, July 17, 2011

String Split Utility

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
//output
split[0]=stringa
split[1]=stringb
split[2]=
split[3]=stringc
split[4]=stringd
split[5]=stringe
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
//output 
split[0]=stringa
split[1]=stringb
split[2]=stringc
split[3]=stringd
split[4]=stringe

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
//output
split[0]= "key:mykey";
split[1]= "Value : test1,test2";
Summary
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.

3 comments:

  1. Excellent information.
    There is one more method for string split in RegularExpression namespace. Static method of RegEx class. Which is best for long strings. Isn't it?

    ReplyDelete
  2. Hi pranay thanks for the information

    ReplyDelete
  3. Good job man, you have covered the topic quite well. I have also blogged about How to split string in Java, let me know how do you find it .

    Thanks
    Javin

    ReplyDelete