On TV.com: BATTLESTAR GALACTICA has fans talking

Count words in VB.NET using Split and Replace functions

Tags: Microsoft development tools, Programming languages, Microsoft Visual Basic.Net, Irina Medvinskaya, strText, Visual Basic Tips Newsletter

  • Save
  • Print
  • Digg This
  • 0

Takeaway: The next time you need to know the number of words in a larger VB.NET string consider using the Split function. This tip provides an example of how to use Split, as well as Replace 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!

  • Save
  • Print
  • Digg This
  • 0

Print/View all Posts Comments on this article

Count Words in VB.NET using Split and Replace functionshugo@...  | 03/09/07
Too rightTony Hopkinson  | 03/09/07
More direct approach?aikimark@...  | 03/09/07

What do you think?

Article Categories

Security
Security Solutions, IT Locksmith
Networking and Communications
E-mail Administration NetNote, Cisco Routers and Switches
CIO and IT Management
Project Management, CIO Issues, Strategies that Scale
Desktops, Laptops & OS
Windows 2000 Professional, Microsoft Word, Microsoft Excel, Microsoft Access, Windows XP,
Data Management
Oracle, SQL Server
Servers
Windows NT, Linux NetNote, Windows Server 2003
Career Development
Geek Trivia
Software/Web Development
Web Development Zone, Visual Basic, .NET

advertisement
Click Here