Working with strings and performing various string operations is important to any Visual Basic developer. Whenever you need to be able to determine the number of words in a larger string, there is a simple VB.NET function that you can use in order to get the necessary result.
The Split function allows you to separate the longer string into words; however, if you have more than one space between words, Split can return an incorrect result. To prevent that from happening, you can use a Replace function before using Split in order to change any occurrence of multiple spaces. Listing A offers an example.
In the example, I create the string strText and set it to a long string of characters. Then I utilize the Replace function in order to replace any occurrence of multiple spaces with one space. This is done to prep the string strText in order to allow you to use the Split function and provide the correct result. Then I pass the strText to the Split function and get the number of words that are included in the strText string. Note: If you skip or comment the loop that removes extra spaces, the result is seven words. With the loop that removes all extra spaces, the result is four words, which is correct.
Miss a tip?
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!