Different ways to use String Split Function

By James H

This method finds all the substrings in a string that are seperated by one or more characters, returning a string array. Split function has more number of overload method where you can specifiy the maximum number of elements in an array to return from the string.

Here i have two important things 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[])

string words = "apple,bat,cat,dog,,fox,Ghost.";
string [] split = words.Split(new Char [] {' ', ','});
Output will be like this

apple
bat
cat
dog

fox
Ghost

If you want to remove the Empty String Please make use of the Overloaded Methods.
Overload method with option

1. String.Split(Char[], StringSplitOptions)

string words = "apple,bat,cat,dog,,fox,Ghost.";
string [] split = words.Split(new Char [] {' ', ','},StringSplitOptions.RemoveEmptyEntries);

The output would b
e like this
apple
bat
cat
dog
fox
Ghost

2.Overload function to split string in limited no. of string

Split(Char[], Int32)

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

If we want to get the key:mykey in string 1 and Value : test1,test2 in string 2.

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

O
utput would be like this

key:mykey
Value:test1,test2
For more information please refer this link in MSDN.


Different ways to use String Split Function  (442 Views)
Create New Account