我将一个String转换为一个char数组,我想知道是否存在一种替换数组中2个或更多值的方法?
我正在做一个家庭作业的String猜谜游戏,用户输入一个句子或单词,然后用户输入一个字母,如果字母是输入的一部分,那么guessString将更新,并替换其“ '加上用户猜中的字母。
例如:
User enters: racer
Original String: racer
Guess String:?????
Please guess a character
User enters: a
Original String: racer
Guess String:?a???
String input = "This is a string";
input = input.toLowerCase();
int inputLength = input.length();
System.out.println("You entered: " + input
+ "\n" + "The string length is: " + inputLength);
String answerString = "?".repeat(inputLength);
int answerStringLength = answerString.length();
System.out.println(answerString);
System.out.println(answerStringLength);
System.out.println("Guess a letter");
String guess = scan.nextLine();
System.out.println(guess);
int guessLength = guess.length();
System.out.println(guessLength);
while (guessLength != 1) {
guess = scan.nextLine();
guessLength = guess.length();
System.out.println(guessLength);
}
System.out.println(guess);
String guessRepeat = guess.repeat(3);
char guessChar=guessRepeat.charAt(2);
System.out.println(guessChar);
int checkGuess = input.indexOf(guess);
char[] answerStringChars = answerString.toCharArray();
answerStringChars[checkGuess]=guessChar;
String newAnswerString = String.valueOf(answerStringChars);
System.out.println(newAnswerString);
If the guessed letter is 'i'
Actual Results:
??i?????????????
Expected Results:
??i??i??????i???
答案 0 :(得分:0)
尝试以下循环替换所有值,而不是仅替换第一个:
char[] answerStringChars = answerString.toCharArray();
for (int i = 0; i < answerString.length(); i++) {
if (input.charAt(i) == guessChar) {
answerStringChars[i] = guessChar;
}
}
String newAnswerString = String.valueOf(answerStringChars);
这应该可以完成工作。