Hello everyone! I have this assignment that says: Create an application to let the user enter a sentence, then calculate how many words there are in that sentence. I know how to count the "Char" in a word (using .Length), but for this assignment, I really have no idea how to count the words in a sentence. What kind of method am I supposed to use for this particular assignment?

7 Years
Discussion Span
Last Post by Stevoni

Have you looked into using the String.Split function?

Do Sentance.Split(" ") and it will return an array with the delimiter being the space, which is exactly what you need. Just take the Array.Length-1 and you have your total number of words.

Otherwise, you'll have to loop through each character in the sentance and determine if it's a space.
I.e.: (Air coded)

Dim WordCount as integer = 0
 For Each cTemp as Char in Sentance.ToArray
  If cTemp = CStr(" ") then WordCount +=1 'Note, not sure CStr is the proper function, may be ChrW

Here is a simpler solution, note you add one because array elements start at 0 not 1. ie if there are 4 words they will be in array elements 0,1,2,3

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim teststr() As String
        Dim NoWords As Int16
        teststr = Trim(TextBox3.Text).Split
        NoWords = UBound(teststr) + 1
        Label4.Text = "Your sentence contains " & NoWords.ToString & " words"
    End Sub

note you add one because array elements start at 0 not 1.

Man, I'm just having a terrible day with programming. I'm going to have to stop working during the week. :-P Thanks for noticing my blunder.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.