我的代码骗我

时间:2013-10-17 15:03:25

标签: arrays vb.net loops for-loop

我正在编写一个代码来检查一个单词中是否有多个相同的字母,所以我将每个字母分成一个数组并编写了这段代码。 “correctGuesses”变量应该是重复字母的数量。数组包含字符串(“H,E,L,L,O”)。

Dim newCharArray() As Char = wordArray(rndNumber).ToCharArray
ReDim Preserve charToString_2(newCharArray.Length - 1)
Dim cBoolean As Boolean = False

For i As Integer = 0 To (newCharArray.Length - 1) Step 1

    charToString_2(i) = newCharArray(i)
    MsgBox(charToString_2(i))

Next



For j As Integer = 0 To (charToString_2.Length - 1) Step 1
    For b As Integer = 0 To (charToString_2.Length - 1) Step 1

        MsgBox("Is " & charToString_2(j) & " = " & charToString_2(b) & "?")

        If j = b Then

            MsgBox(j & " is equal to " & b & ", continuing.")
            Exit For

        End If
        If CStr(charToString_2(b)) = CStr(charToString_2(b)) Then

            MsgBox("Yes, +1")
            correctGuesses += 1
            charToString_2(b) = "Replaced"
            cBoolean = True

        End If

        MsgBox("No, Continuing.")

    Next                    
Next

第一个if语句有效,所以只要j = b,它就会退出并继续。但接下来的循环,它检查“E”是否等于“H”,它返回true!我不明白为什么!

2 个答案:

答案 0 :(得分:0)

你的算法几乎就在那里。你可以调整一下。

Dim stringtoCheck As String = wordArray(rndNumber)

For j As Integer = 0 To (stringtoCheck.Length - 2)
    For b As Integer = j+1 To (stringtoCheck.Length - 1)

        If stringtoCheck.chars(b) = stringtoCheck.chars(j) Then

            correctGuesses += 1
            cBoolean = True

        End If

    Next                    
Next

答案 1 :(得分:0)

这为字符串中的不同字符提供计数。展示了套管。

    Dim wordToCheck As String = "heLlo racecar" 'note L and l
    Dim lettercounts As New Dictionary(Of Char, Integer)
    For Each c As Char In wordToCheck ' .ToUpperInvariant '.ToLowerInvariant
        If Not lettercounts.ContainsKey(c) Then
            Dim ct As Integer = wordToCheck.Count(Function(ch) ch = c)
            lettercounts.Add(c, ct)
        End If
    Next

    'show the counts
    For Each ltrct As KeyValuePair(Of Char, Integer) In lettercounts
        Debug.WriteLine(String.Format("{0}  {1}", ltrct.Key, ltrct.Value))
    Next