Friday, April 24, 2009

Split function with characters and string (c# string handling)

C# provides Split function to handle string operation in efficient way. Split function is used with character and strings. Here I am showing the different ways in which split function used in programming.

string objstr = “One . Two , Done , Three : Four ,Done”;

Split by Character Array
string[] split1 = objstr.Split(new Char[] {',', '.', ':' });

Description : Split function will return array of substring splited by all character (‘,’,’.’,’:’) which are specified in char array.
Result : split1[6] = {“One”,”Two”,”Done”,”Three”,”Four”,”Done”}


Split by Character
string[] split2 = objstr.Split(',');

Description : Split function will return array of substring splited by character (’,’) which are specified in char array.
Result : split2 [4]= { “One . Two”,“Done”,“Three : Four”,”Done” }

Split by Character Array and count
string[] split3 = objstr.Split(new Char[] { ',' }, 2);

Description : Split function will return array of substring splited by character (’,’) which are specified in char array and count (2) will specify no. of substrings.
Result : split3 [2]= { “One . Two”,“Done , Three : Four ,Done” }

Split by Character Array and StringSplitOptions options (none)
string[] split4 = objstr.Split(new Char[] { ',' }, StringSplitOptions.None);

Description : Split function will return array of substring splited by character (’,’) which are specified in char array and StringSplitOptions.None will return all substring included empty substrings.
Result : split4 [4]= { “One . Two”,“Done”,“Three : Four”,”Done” }

Split by Character Array and StringSplitOptions options (RemoveEmptyEntries)
string[] split5 = objstr.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

Description : Split function will return array of substring splited by character (’,’) which are specified in char array and StringSplitOptions.None will return all substring without empty substrings.
Result : split5 [4]= { “One . Two”,“Done”,“Three : Four”,”Done” }

Split by String Array and StringSplitOptions options (none)
string[] split6 = objstr.Split(new string[] { "Done" }, StringSplitOptions.None);

Description : Split function will return array of substring splited by string (’Great !!’) which are specified in string array and StringSplitOptions.None will return all substring included empty substrings.
Result : split6 [3]= { “One . Two ,”,”, Three : Four ,”,””}

Split by String Array and StringSplitOptions options (RemoveEmptyEntries)
string[] split7 = objstr.Split(new string[] { " Done" }, StringSplitOptions.RemoveEmptyEntries);

Description : Split function will return array of substring splited by string (’Great !!’) which are specified in string array and StringSplitOptions.None will return all substring without empty substrings.
Result : split7 [2]= { “One . Two ,”,”, Three : Four ,”}

No comments:

Post a Comment