Tuesday, November 21, 2017

Split string by one or multiple characters (c# / .NET)


Splitting string to string array is a very common and frequent task in development. Here are some ways to split string by one or multiple characters.

Split string by one character


Lets split the following sentence by ','
            string str = "my,name,is,computer";
     string[] charArray = str.Split(',');

Also, you can split string my multiple characters
            string str = "my,name-is,computer";
     char[] splitCharArray = new char[] { ',', '-' };
     string[] charArray = str.Split(splitCharArray);

Split string by multiple characters


lets split the following sentence by string(s)
string str = "my&&name&&is%%computer";
string[] splitStringArray = new string[] { "&&"}; 
string[] charArray = str.Split(splitStringArray,StringSplitOptions.None);

Try this and check the difference

 string str = "my&&name&&is%%computer";
 string[] splitStringArray = new string[] { "&&", "%%" }; // strings to split the sentence
 string[] charArray = str.Split(splitStringArray,StringSplitOptions.None);


No comments:

Post a Comment