我在下面有以下子项。它的作用是从用户输入的文本框中获取输入,用特定数值替换每个字母,显示每个单词的总数,然后显示整个输入的总数。例如,如果用户键入a bbb e,则txtbox5中的输出为:
aa = 40
bbb = 90
e = 40
Total 170
如果用户输入一个长句,则可以正常工作。所以我想以相同的方式分别计算每个句子,句子的分隔符可以是句号或逗号。如果用户输入aa bbb。 ff ee。输出应该
aa = 40
ccc = 90
Total for the 1st sentence = 120
ff = 100
ee = 80
Total for the 2nd sentence = 180
and so forth
Private Sub Calculate(ByVal input As String)
Dim total As Integer = 0
Dim wordTotal As Integer
Dim dicLetters As New Dictionary(Of Char, Integer)
dicLetters.Add("A", 20)
dicLetters.Add("B", 30)
dicLetters.Add("E", 40)
dicLetters.Add("F", 50)
Dim charValue As Integer
For Each word As String In input.Split(New Char() {" "})
wordTotal = 0
For Each character As Char In word
wordTotal += If(dicLetters.TryGetValue(character, charValue) = _
True, dicLetters(character), 0)
Next
total += wordTotal
txtBox5.Text += word.PadRight(12) + " = " + _
wordTotal.ToString().PadLeft(5) + vbNewLine
Next
txtBox5.Text += "Total:".PadRight(12) + " = " + _
total.ToString().PadLeft(5)
End Sub
答案 0 :(得分:2)
使用Split方法创建句子数组。它将接受一系列分隔符。遍历数组并将每个句子和句子的索引传递给子例程。在子例程中添加一个整数参数作为句子编号,并更改输出字符串。
这样的事情:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Sentences() As String = TextBox1.Text.Split({","c,"."c})
For I = 0 to Sentences.Count-1
Calculate(Sentences(I), I+1)
Next
End Sub
Private Sub Calculate(ByVal input As String, ByVal index As Integer)
Dim total As Integer = 0
Dim wordTotal As Integer
Dim dicLetters As New Dictionary(Of Char, Integer)
dicLetters.Add("A", 20)
dicLetters.Add("B", 30)
dicLetters.Add("E", 40)
dicLetters.Add("F", 50)
Dim charValue As Integer
For Each word As String In input.Split(New Char() {" "})
wordTotal = 0
For Each character As Char In word
wordTotal += If(dicLetters.TryGetValue(character, charValue) = _
True, dicLetters(character), 0)
Next
total += wordTotal
txtBox5.Text += word.PadRight(12) + " = " + _
wordTotal.ToString().PadLeft(5) + vbNewLine
Next
txtBox5.Text += "Total for sentence " + index.ToString +" :" + " = " + _
total.ToString().PadLeft(5)
End Sub