Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Visual Basic [VB] (http://www.go4expert.com/articles/visual-basic-tutorials/)
-   -   Use Replace & Split to count words in VB.Net (http://www.go4expert.com/articles/replace-split-count-words-vbnet-t3608/)

pradeep 26Mar2007 11:33

Use Replace & Split to count words in VB.Net
 
Whenever need to know the number of words in a larger VB.NET string consider using the Split function. In this 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. Snippet A offers an example.

Snippet A
Code: VB

Private Sub CountWords()
     Dim strText As String = "It's a wonderful    world"
     Dim iCount As Integer
 
 
     Do While (strText.IndexOf(Space(2)) >= 0)
         strText = strText.Replace(Space(2), Space(1))
     Loop
 
 
     iCount = Split(strText, Space(1)).Length
     MsgBox(iCount.ToString())
 End Sub

As in the example, create the string strText and set it to a long string of characters. Then utilize the Replace function in order to replace any occurrence of multiple spaces with one space. This is done to prepare the string strText in order to allow you to use the Split function and provide the correct result. Then pass the strText to the Split function and get the number of words that are included in the strText string.

Note: If you remove 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.


All times are GMT +5.5. The time now is 04:36.