2013-10-17 30 views
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」,並且它返回true!我不知道爲什麼!

+1

你有b作爲參數在兩邊。 –

+0

該死的總是那麼明顯,我很慚愧。 –

+0

@ 500-InternalServerError爲什麼不只是作爲答案發布? – Gray

回答

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 
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