Mrquestion Mrquestion - 2 months ago 7
Vb.net Question

How to get second match from string on Visual Basic?

I'm doing Hangman Game in Visual Basic. I'm looking for typing a letter in a TextBox and clicking a button to check out. If that letter is in String, it will return position but when the word has two matches... How could I do it?

Next code only return the first match, I mean, only position of the first "A".

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


Thank for your help

EDIT: Sorry, I didn't say it, I can't use arrays.

Answer

Since you don't look like you know much of the language. I'll make you a sample that might help you.

You could see your problem the other way around, instead of looking if the choosen letter is in the word, look if each character of the word is the choosen letter.

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

This would be much easier with arrays of label and loops.