2 回答

TA貢獻1780條經驗 獲得超5個贊
假設您有一個開始String,例如Italia.
用戶輸入字母i,應該發生的事情是
------ > I---i-
讓我們首先將待猜測的版本String轉換為虛線版本
final String toBeGuessed = "Italia"; // Italia
final String dashed = toBeGuessed.replaceAll(".", "-"); // ------
現在用戶輸入i一個猜測的字母。我們將其轉換為小寫以供以后比較。
final char letter = Character.toLowerCase('i');
我們需要做的是更新虛線String,為此我們將使用StringBuilder.
使用 aStringBuilder允許我們設置單個字符。
// Create the StringBuilder starting from ------
final StringBuilder sb = new StringBuilder(dashes);
// Loop the String "Italia"
for (int i = 0; i < toBeGuessed.length(); i++) {
final char toBeGuessedChar = toBeGuessed.charAt(i);
// Is the character at the index "i" what we are looking for?
// Remember to transform the character to the same form as the
// guessed letter, maybe lowercase
final char c = Character.toLowerCase(toBeGuessedChar);
if (c == letter) {
// Yes! Update the StringBuilder
sb.setCharAt(i, toBeGuessedChar);
}
}
// Get the final result
final String result = sb.toString();

TA貢獻1818條經驗 獲得超8個贊
由于在 Java 中字符串是不可變的,因此您不能用另一個字符串替換任何字符串。
hintsQuestionString = hintsQuestionString.replace(hintsQuestionString.charAt(k), letterChar);
上面的行在 Java 中不起作用。
您可以使用 StringBuilder 類來替換字符串
或者
您不必吐出字符串,因為它在 Java 中不起作用,因為 Java 中的 String 類是不可變的。
您可以簡單地在 TextView 中設置文本
你從用戶那里得到的這個字符串 String hintsQuestionString = hintsQuestion.getText().toString();
然后使用 equals 方法比較整個字符串,如果輸入的字符串匹配,則必須設置文本。我自己取了 countryName 變量,你必須用你取的變量替換這個字符串。
if(countryName.equals(hintsQuestionString)) { hintsQuestion.setText(hintsQuestionString); }
我希望這能幫到您。
添加回答
舉報