2016-09-28 95 views
1

我最近開始使用Visual Basic,所以我對它不是很熟悉。我對計算很陌生,所以請耐心等待!我試圖製作一個計算句子中特定單詞的表單程序。從我的代碼中可以看到,我對它沒有太多瞭解。我所要做的就是告訴我兩個文本框是否匹配。如果有人能幫助我解決問題,我將非常感激!非常感謝。VB程序,用於統計句子中特定單詞的出現次數

代碼:

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 

回答

0

VB.NET和C#中使用相同的底層對象模型,這樣你就可以適應的exising C# solution

這是你的子會怎樣看:

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 

這種方法計算所有ocurrences一氣呵成,沒有一個循環,所以你不需要的遞增器。

As @ romulus001提到,Word.Text的長度可能爲零,所以在除以之前應該檢查它。如果Word.Text的長度爲零,那麼你想要的數量可能是零,因爲你幾乎沒有找到任何東西。

+0

如果Word字段爲空,該怎麼辦?你不能分0 – romulus001

+0

非常感謝,真的很感謝 –

+0

沒問題,很高興我們可以提供幫助。 –

0

我不知道這是否是必須區分大小寫或沒有,但你可以使用這些代碼之一:

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` 

然後:

Counter1.Text = Counter 
相關問題