0

我正在编写一个代码来检查一个单词中是否有多个相同的字母,所以我将每个字母分成一个数组并编写了这段代码。“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”,并返回真!我不知道为什么!

4

2 回答 2

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
于 2013-10-17T17:48:55.550 回答
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
于 2013-10-17T19:07:01.900 回答