【问题标题】:Comparing string with array比较字符串和数组
【发布时间】:2013-02-01 04:57:27
【问题描述】:

我正在尝试使用 Visual Basic 中的 for 循环将字符串变量与字符串数组的元素进行比较。我按顺序将用户输入的字符串变量与具有小写字母的数组进行比较。我有一些逻辑错误,因为我的“计数”变量出于某种原因总是在 25,因此它总是说“抱歉,再试一次”,除非用户键入 Z。请帮助!

 Dim lower() As String = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",    "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
   For count As Integer = 0 To 25
        input = txtInput.Text
        input = input.ToLower
        If input.Equals(lower(count)) Then
            txtResult.Text = "Correct"
        Else
            txtResult.Text = "Sorry, Try again"
        End If
    Next

【问题讨论】:

    标签: arrays vb.net string for-loop


    【解决方案1】:

    问题是您应该在找到匹配项后退出循环(使用exit for)。否则,任何不匹配的字符都会将 txtResults.Text 重置为“抱歉,重试”。例如,当您输入“f”时,txtResults.Text 设置为“正确”。但是当你到达 g 时,当前,它会将 txtResults.Text 更改为“对不起,再试一次。”,以及 h、i 等。

    这是一个很好的编程练习,但是你可以使用一个捷径:

    lower.contains(input.lower)
    

    信息:

    http://msdn.microsoft.com/en-us/library/dy85x1sa.aspx

    【讨论】:

      【解决方案2】:

      欢迎来到 StackOverflow!

      只有在键入“z”时才能得到“正确”结果的原因是“z”是数组的最后一项。如果键入“y”,count = 24 (lower(24) = "y") 的结果将是正确的,但在下一步它会将“y”与 lower(25) 进行比较,实际上是“z”。所以txtResult.Text 将被“抱歉,重试”覆盖。

      当我正确完成您的任务时,您想检查输入字符串是否存在于数组中。为此,您可以使用Array.Contains 方法:

      Dim lower() As String = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",    "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
      Dim input As String = txtInput.Text
      If (lower.Contains(input)) Then
          txtResult.Text = "Correct"
      Else
          txtResult.Text = "Sorry, Try again"
      End If
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-14
        • 2020-08-07
        • 2021-12-06
        • 1970-01-01
        相关资源
        最近更新 更多