Different ways to use String Split Function in .NET

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 be 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);
Output would be like this

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

Popular posts from this blog

Exporting to excel from a custom class object using C#.NET

Get the Clicked Cell Value and Column Name of GridView in ASP.NET

How to hide bootStrap popover when user click(s) outside the popover?