【发布时间】:2018-12-02 19:38:25
【问题描述】:
我目前正在为家庭作业做一个 soundex 系统。对于作业,我需要用某些数字替换某些字母。对于作业,我使用的是 do 循环。问题是字符串中只有一个字母被数字替换,而除了第一个字母之外的其余字母被删除。例如,罗伯特应该以“R163”的形式出现,但它却以“R300”的形式出现。我想知道我做错了什么。我的代码是:
Private Sub btnCompute_Click(sender As Object, e As EventArgs) Handles btnCompute.Click
Dim word As String = txtInput.Text
Dim first As String = txtInput.Text.Substring(0, 1)
Dim rest As String = txtInput.Text.Substring(1, word.Length - 1)
Dim test As String = ""
Dim combine As String = ""
Dim i As Integer = 0
Do
Select Case rest.Substring(i)
Case "a", "e", "i", "o", "u", "h", "y", "w"
test &= ""
Case "b", "f", "p", "v"
test &= "1"
Case "c", "g", "j", "k", "q", "s", "x", "z"
test &= "2"
Case "d", "t"
test &= "3"
Case "l"
test &= "4"
Case "m", "n"
test &= "5"
Case "r"
test &= "6"
End Select
i += 1
Loop Until i > rest.Length
combine = first & test
If combine.Length < 4 Then
Do While combine.Length < 4
combine &= "0"
Loop
ElseIf combine.Length > 4 Then
combine = combine.Substring(4)
End If
txtSound.Text = combine
End Sub
【问题讨论】:
-
针对具体情况使用最合适的循环。在这种情况下,这将是一个
For Each或者可能是一个For循环。您还应该阅读您正在调用的Substring方法的文档。它不会做你认为它会做的事情。如果你只想要一个字符,那么直接索引String。
标签: vb.net loops while-loop