Useful overloads for String.Split()

Most of C# developers are familiar with this String.split() method. I have found some useful overloads for split method of the string class split the string in array of string.

Example 1:

String.Split( char[])

Code:
string words = "string1,string2,string3,,string4 string5.";
string [] split = words.Split(new Char [] {' ', ','});

Above code create a string array which has

//result
split[0]=string1
split[1]=string2
split[2]=string3
split[3]=
split[4]=string4
split[5]=string5

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)

Code:
string words = "string1,string2,string3,,string4 string5.";
string [] split = words.Split(new Char [] {' ', ','},StringSplitOptions.RemoveEmptyEntries);

Return split array->

//result
split[0]=string1
split[1]=string2
split[2]=string3
split[3]=string4
split[4]=string5

Example 2:

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

string a = "key:Testkey, Value : testValue1,testValue2";

Now I have to get the key:Testkeyin string 1 and Value : testValue1,testValue2in string 2.
Overload function to split string in limited no. of string

Split(Char[], Int32)

Code:
string a = "key: Testkey, Value : testValue1,testValue2";
string [] split = words.Split(new Char [] {','},2);

Return split array->

//result
split[0]= "key: Testkey";
split[1]= "Value : testValue1,testValue2";

For more information:
String.Split Method (Char(), Int32):
http://msdn.microsoft.com/en-us/library/c1bs0eda.aspx

String.Split Method (Char(), Int32, StringSplitOptions):
http://msdn.microsoft.com/en-us/library/ms131450.aspx

Comments

Popular posts from this blog

The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

How can I get a value of a property from an anonymous type (C#)

Check/Uncheck all items in a CheckBoxList using Javascript