2016-10-10 87 views
0

我正在寫一個簡單的hang子手程序,我想替換存儲已找到的單詞的字母的變量中的某些內容。Visual Basic替換不起作用

下面是代碼:

Replace(wordLettersFound, Mid(wordLettersFound, counter, 1), letter) 

wordLettersFound,計數器和信是我使用的變量3。

該腳本之前的變量都是下劃線,但它不會改變!誰能幫我這個?

P.S. 我不知道我使用的是什麼版本的VB,visual studio community 2015只是說'visual basic'。

+1

你正在開發VS 2015中的應用程序,但你使用的是舊的Replace()和Mid()函數在VS 2008的版本中? –

+0

@AndrewMorton:我很清楚這一點,但我認爲不應該習慣這些老方法,因爲他們有一天可能會被刪除。 - 我認爲所有這些舊方法都應放在compability命名空間中,並重寫文檔教程以包含新方法。 –

+0

@VisualVincent使用VB.NET方法而不是框架方法有很多好處,但我們不要在這個問題上去那裏。 –

回答

0

有另一種替換字符串中的字符的方法。使用替換功能在你的情況下有點尷尬,因爲在開始時,全部這些字符都是下劃線 - 替換爲你使用的將會用所找到的字符替換它們。

相反,您可以將字符串剪切到所需替換的左側,添加替換字符,然後添加字符串的其餘部分。該行是註釋後的一個「砍foundWord起來,把人物在正確的地方」,在此代碼:

Module Module1 

    Sub Main() 
     Dim wordToFind = "alphabet" 
     ' make a string of dashes the same length as the word to find 
     Dim foundWord = New String("-"c, wordToFind.Length) 

     While foundWord <> wordToFind 
      Console.Write("Enter your guess for a letter: ") 

      Dim guess = Console.ReadLine() 
      ' make sure the user has only entered one character 
      If guess.Length = 1 Then 
       ' see if the letter is in the string 
       Dim pos = wordToFind.IndexOf(guess) 
       While pos >= 0 
        ' chop foundWord up and put the character in the right place 
        foundWord = foundWord.Substring(0, pos) & guess & foundWord.Substring(pos + 1) 
        ' see if there are any more of the same letter 
        pos = wordToFind.IndexOf(guess, pos + 1) 
       End While 

       ' show the user the current progress 
       Console.WriteLine(foundWord) 
      Else 
       Console.WriteLine("Please enter just one letter!") 
      End If 

     End While 

     Console.WriteLine("You did it!") 

     Console.WriteLine("Press enter to leave the program.") 
     Console.ReadLine() 

    End Sub 

End Module 

注:不要直接使用所有的代碼作業,因爲你的老師找到這個。這就是其他人在做功課 - 你知道你是誰)

2

Replace不會修改字符串,但返回一個新的字符串替換,所以你應該把它賦值給變量:

wordLettersFound = Replace(wordLettersFound, Mid(wordLettersFound, counter, 1), letter) 
+0

謝謝,我的代碼現在改變了字母,但是改變的字母恰好位於最後一個改變後的字母之後,而不是位於正確的位置,例如。船是sp__而不是s__p。這裏是代碼: –

+0

If Mid(wordLettersFound,counter,1)=「_」然後 wordLettersFound =替換(wordLettersFound,Mid(wordLettersFound,counter,1),letter,1,1,0) End If –

0

另一種方法代替,

Dim theLetters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzAAA" 

    theLetters = theLetters.Replace("A"c, "@"c) 
+0

結果是? –

+0

啊,是的,但我想要替換一個特定的部分,而不是所有的字符串。 –

+0

你是指什麼節?一羣人物? – dbasnett