将String与数组中的字符串进行比较

时间:2013-04-25 15:26:45

标签: vb.net

我正在尝试使用此脚本将文本框中的用户输入与22个正确的单词进行比较。我不是在寻找多个案例,例如VICE位于ADVICE中,因此它将是2个值; 我希望它让字符串值只接受相等的值

目前,它只识别第一个单词TIED并显示一个“找到”的消息框,但它不会识别列表中的任何其他单词。

我用visual basic script编写

Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
    Dim StrCorrect() As String = {"TIED", "VICE", "ICED", "DIVE", "DIET", "DATE", "CITE", "CAVE", "AIDE", "ACED", "CITED", "ACTED", "VACATE", "CATTIE", "ADVICE", "AVIATE", "ACTIVE", "VACATED", "DICTATE", "AVIATED", "ACTIVATE", "ACTIVATED"}
    Dim Find As String = userinput
    For Each Str As String In StrCorrect
        If StrComp(Str, userinput, CompareMethod.Text).ToString = 0 Then
            MsgBox("Found" & userinput)
            Return
        Else : MsgBox("incorrect word")
            Return
        End If
    Next
End Sub

4 个答案:

答案 0 :(得分:1)

问题是如果第一项不匹配,则显式返回循环。如果你的循环完成而没有找到,你只知道你没有匹配,所以请尝试这样的事情:

For Each Str As String In StrCorrect
    If StrComp(Str, userinput, CompareMethod.Text).ToString = 0 Then
        MsgBox("Found" & userinput)
        Return
    End If
Next

MsgBox("incorrect word")

如果列表中的所有项目未能通过第一次测试,则只会显示“错误的字词”。

答案 1 :(得分:0)

为什么STRCOMP?如果你想要完全匹配,为什么不直接比较?

    For Each Str As String In StrCorrect
        If Str = Find Then
            MessageBox.Show("Found :" & Str)
        End If
    Next

答案 2 :(得分:0)

我会使用for循环,比如

For i As Integer = 0 To StrCorrect.Length - 1
        If StrCorrect(i) = Find Then
            MsgBox("Found" & Find)
            Return
        'End if

        'The else statement simply alerting that it didnt find the right word on this iteration
        'The else can be removed if you dont want this alert
        Else
            MsgBox("incorrect word")
            'Return
        End If
Next

答案 3 :(得分:0)

尝试如下,它会帮助你...

示例:

Dim result As String() = Array.FindAll(StrCorrect, Function(s) s.Equals(Find))
If (result.Length > 0) Then
  MsgBox("Found : " & userinput)
Else
  MsgBox("incorrect word")
End If

完整代码:

Dim StrCorrect() As String = {"TIED", "VICE", "ICED", "DIVE", "DIET", "DATE", "CITE", "CAVE", "AIDE", "ACED", "CITED", "ACTED", "VACATE", "CATTIE", "ADVICE", "AVIATE", "ACTIVE", "VACATED", "DICTATE", "AVIATED", "ACTIVATE", "ACTIVATED"}
Dim Find As String = userinput
Dim result As String() = Array.FindAll(StrCorrect, Function(s) s.Equals(Find))
If (result.Length > 0) Then
  MsgBox("Found : " & userinput)
Else
  MsgBox("incorrect word")
End If