1

I have recently started with Visual Basic so I am not very familiar with it. I am new to computing so bear with me! I am attempting to make a form program that counts a specific word in a sentence. I haven't got very far with it as you can see from my code. All I have got it to do is tell me if the two text boxes match. I would really appreciate it if anyone could help me with a solution! Many thanks.

code:

Public Class Form1
    Dim Counter As Integer = 0

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

        If Word.Text = Sentence.Text Then
            Counter1.Text = Counter + 1
        End If
    End Sub

End Class
Robert Columbia
  • 6,313
  • 15
  • 32
  • 40

2 Answers2

0

VB.NET and C# use the same underlying object model, so you can adapt an exising C# solution.

Here's how your sub would look:

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

    If Word.Text.Length = 0 Then
        counter = 0
    Else
        counter = ( Sentence.Text.Length - Sentence.Text.Replace(Word.Text,"").Length ) / Word.Text.Length
    End If
    Counter1.Text = counter
End Sub

This method counts all ocurrences in one go, without a loop, so you don't need an incrementor.

As @romulus001 mentions, the length of Word.Text could be zero, so this should be checked before dividing by it. If the length of Word.Text is zero, then the count you want is probably zero since you are literally looking for nothing.

Community
  • 1
  • 1
Robert Columbia
  • 6,313
  • 15
  • 32
  • 40
0

I don't know if it must be case sensitive or not, but you can use one of these codes :

1)

Counter = Sentence.Text.split(Word.Text).Length - 1 'if the search is case sensitive

2)

Counter = Sentence.Text.toUpper.split(Word.Text.toUpper).Length - 1 'if the search is NOT case sensitive`

then:

Counter1.Text = Counter
Visual Vincent
  • 18,045
  • 5
  • 28
  • 75
romulus001
  • 318
  • 3
  • 15