A string can be split into an array of strings using String.Split() method. It returns a string array that contains the substrings of this orignal string instance that are delimited by elements of a specified character.
Let us suppose an user input field is filled in an irregular manner with more than a single space between words and we have to select only valid words (not empty spaces) and process them there after:
If we will go for simple Split then this would be the result.
string myText = txtSearch.Text.ToString(); //Lets say myText will have value "This is the StringSplitOptions demo" string[] wordSearched = myText.Split(' '); //Split at each occurance of a whitespace. for (int ctWords = 0; ctWords < wordSearched.Length; ++ctWords) { Console.WriteLine("string " + ctWords + " : " + wordSearched[ctWords]); }
Output
string 0 : This string 1 : is string 2 : string 3 : the string 4 : string 5 : string 6 : StringSplitOptions string 7 : string 8 : string 9 : demo
To remove the empty values, we need to just add the second parameter to the Split method.
char[] charSeparators = new char[] { ' ' }; string[] wordSearched = myText.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
Now the Output will be:
string 0 : This string 1 : is string 2 : the string 3 : StringSplitOptions string 4 : demo
String.Split method is overloaded and String.Split(Char[], StringSplitOptions) is one of them.
The first parameter is an array of Unicode characters that delimits the substrings in this string and second parameter decides whether to return a empty element or not.
Specify the None value to invoke the default behavior of the Split method, which is to return an array of both empty and that are not empty. Specify the RemoveEmptyEntries value to cause the Split method to return an array consisting solely of substrings that are not empty.