Splitting Text into Words
Mon, Sep 21 2009 14:25
There are times when you need to work with a set of text as individual words. For example, you need to count the occurrence of each word or convert the first letter of each word to a capital letter or randomly pick specific words.
One easy way to convert a set of text into individual words is to use the Split function. (Another option is to use Regular Expressions, but that is a different post.)
string wordArray= textBox1.Text.Split(' ');
Dim wordArray() As String = TextBox1.Text.Split(" "c)
In both examples, the text entered by the user into TextBox1 is split into words and each word is stored in a position of the array.
The split parameter is a char value. In VB, you define a char using the small "c" after the single character string: Split(" "c). In C#, you define a char using single quotes instead of double quotes: Split(' ').
For example, say the user enters this:
"That that is, is. That that is not, is not. Is that it? It is."
The contents of the array then looks like this:
From here you can then work with the individual words as array elements.