Vb.net 如何在VisualBasic上从字符串中获取第二个匹配?
我正在用visualbasic做刽子手游戏。我想在文本框中键入一封信,然后单击按钮进行签出。如果该字母在字符串中,它将返回位置,但当单词有两个匹配项时。。。我怎么做呢 下一个代码只返回第一个匹配,我的意思是,只返回第一个A的位置Vb.net 如何在VisualBasic上从字符串中获取第二个匹配?,vb.net,if-statement,indexof,select-case,Vb.net,If Statement,Indexof,Select Case,我正在用visualbasic做刽子手游戏。我想在文本框中键入一封信,然后单击按钮进行签出。如果该字母在字符串中,它将返回位置,但当单词有两个匹配项时。。。我怎么做呢 下一个代码只返回第一个匹配,我的意思是,只返回第一个A的位置 Dim palabra As String = "PALABRA" Private Sub BtnComprobar_Click(sender As Object, e As EventArgs) Handles BtnComprobar.Click If t
Dim palabra As String = "PALABRA"
Private Sub BtnComprobar_Click(sender As Object, e As EventArgs) Handles BtnComprobar.Click
If txtComprobar IsNot "" Then
Dim letra As String = UCase(txtComprobar.Text)
If palabra.IndexOf(letra) > -1 Then
Select Case palabra.IndexOf(letra)
Case 0
Lbl1.Text = letra
LblP.ForeColor = Color.Red
Case 1
Lbl2.Text = letra
LblA.ForeColor = Color.Red
Case 2
Lbl3.Text = letra
LblL.ForeColor = Color.Red
Case 4
Lbl4.Text = letra
Case 5
Lbl5.Text = letra
LblB.ForeColor = Color.Red
End Select
Else
errores += 1
txtErrores.Text = CStr(errores)
End If
txtComprobar.Text = ""
End If
End Sub
谢谢你的帮助
编辑:对不起,我没说,我不能使用数组。将字符串放入数组并循环遍历每个字母。当存在匹配时返回位置,但继续循环,直到您完成整个数组。因为您看起来不太懂该语言。我会给你做一个可能对你有帮助的样品 你可以从另一个角度来看待你的问题,而不是看单词中是否有选择的字母,而是看单词的每个字符是否都是选择的字母
If palabra.IndexOf(letra) > -1 Then
If palabra(0) = letra Then
Lbl1.Text = letra
End If
If palabra(1) = letra Then
Lbl2.Text = letra
End If
If palabra(2) = letra Then
Lbl3.Text = letra
End If
If palabra(3) = letra Then
Lbl4.Text = letra
End If
If palabra(4) = letra Then
Lbl5.Text = letra
End If
If palabra(5) = letra Then
Lbl6.Text = letra
End If
Else
errores += 1
txtErrores.Text = CStr(errores)
End If
使用标签和循环数组会容易得多。将此函数添加到代码中:
Public Function GetIndexes(ByVal SearchWithinThis As String, ByVal SearchForThis As String) As List(Of Integer)
Dim Result As New List(Of Integer)
Dim i As Integer = SearchWithinThis.IndexOf(SearchForThis)
While (i <> -1)
Result.Add(i)
i = SearchWithinThis.IndexOf(SearchForThis, i + 1)
End While
Return Result
End Function
Dim Indexes as list(of Integer) = GetIndexes(palabra, letra)
现在GetIndexes将找到您要查找的字母的所有索引,并将它们放入列表索引中。IndexOf has,IndexOfchar,n将找到n之后的第一个字符索引。我这样做了:ElseIf palabra.IndexOfletra,indice>-1然后选择Case palabra.IndexOfletra,标记,但它没有找到最后一个匹配项。不是==C运算符吗?@Cal cium是。。。没有足够的咖啡因