Count words in VB.NET using Split and Replace functions

The next time you need to know the number of words in a larger VB.NET string consider using the <i>Split</i> function. This tip provides an example of how to use <i>Split</i>, as well as <i>Replace</i> if you have more than one space between words.

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?

Check out the Visual Basic archive, and catch up on the most recent editions of Irina Medvinskaya's column.

Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!

Editor's Picks