【问题标题】:Loop won't concatenate a string more than once循环不会多次连接字符串
【发布时间】: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


【解决方案1】:

尽量保持与您的示例相似...这应该可行。

    Dim word As String = txtInput.Text
    Dim test As String = String.Empty
    Dim combine As String = String.Empty

    For i As Integer = 1 To word.Length - 1
        Select Case word.Substring(i, 1)
            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
    Next

    combine = (word.Substring(0, 1) & test).PadRight(4, "0")
    txtSound.Text = combine

【讨论】:

    猜你喜欢
    • 2016-12-15
    • 2017-12-18
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 2015-07-27
    • 2013-07-07
    • 2016-02-22
    • 1970-01-01
    相关资源
    最近更新 更多