How many words in my textbox?

caesarmx

New member
Joined
May 2, 2007
Messages
2
Programming Experience
Beginner
the user wrote some words in the multiline textbox, i want to write a code on the (click button) event, the result of this action msgbox tell him-user-how many words he is actuly wrote.

my idea was
( declare for example x as string & x=" " )here i have a value of x which equal one space" ", if i could count number of x in the text i will know how many words by adding 1 to number of x)
it was my thought but any method will help .
thanks for reading
 
Solution

You need to count the spaces and line feeds (if user pressed Enter for a new line or paragraph), eliminate any duplicate spaces and line feeds. Here is the working code:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim x As Integer = 0, sp As Integer = 0, par As Integer = 0
Dim sent As String = TextBox1.Text
sent = sent.Trim() 'remove leading & trailing spaces
sent = sent.Trim(Chr(13)) 'remove leading & trailing line feeds
sent = sent.Replace(vbCrLf, " ") 'replace line feeds with spaces

Do
sent = sent.Replace(" ", " ") 'remove duplicate spaces
Loop Until sent.IndexOf(" ") = -1

Do
x += 1 'counter for number of words
sp = sent.IndexOf(" ", sp + 1) 'locate next space
Loop Until sp = -1

MessageBox.Show("Number of words = " & x)
End Sub
 
Last edited:
Back
Top