1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Use Replace & Split to count words in VB.Net

Discussion in 'Visual Basic [VB]' started by pradeep, Mar 26, 2007.

  1. pradeep

    pradeep Team Leader

    Apr 4, 2005
    Likes Received:
    Trophy Points:
    Kolkata, India
    Home Page:
    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
     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))
         iCount = Split(strText, Space(1)).Length
     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.

Share This Page