0
private String theLetters = "_ _ _ _ _\n";
StringBuilder myName = new StringBuilder(theLetters);
for(char e : theSecretWord.toLowerCase().toCharArray())
{
if(e == theUsersGuess.charAt(0))
{
int index = theSecretWord.indexOf(e) * 2;
myName.setCharAt(index, theUsersGuess.charAt(0));
theLetters = myName.toString();
}
}
由於某些原因,這將僅替換字符串theSecretWord中第一個出現的字母,而不是第二個,即使每個循環的這個字符都會經過每個字符並相應地在信件中進行替換。我不明白爲什麼它不會取代一封以上的信件。如何替換字符串中第二次出現的字符? (Java)
我認爲這是因爲循環一旦找到匹配的字母即使它不應該停止。
看絃樂的文檔:http://docs.oracle.com/javase/7/docs/api/java/lang /String.html#indexOf(int)indexOf(char)總是給你第一個出現 – mdewitt
你的問題已經在這裏解決了:http://stackoverflow.com/questions/5034442/java-indexes-of-all-occurrences-of -character-in-a-string – Lotus
是的,你是對的@mdewitt我完全忘了那個。 –