是否可以用另一个字符串中的字符替换字符串中的字符?

时间:2018-07-11 18:40:24

标签: java string

如果我有一个存储问题答案的字符串以及一个用下划线隐藏答案的for循环,是否可以用用户的猜测替换并显示字符串答案中的字符,或者以某种方式更改字符串答案仅显示用户的正确猜测?这是我的代码的一部分:

String answer = "December"; // this is the phrase i want hidden with 
//underscores
for loop( int i = 0; i < answer.length(); i++){
System.out.println("_"); // hides phrase with underscores
System.out.print("What is your guess for this round?");
String userGuess = console.next();
char ch = answer.charAt(i);
if (userGuess.indexOf(ch) != -1) { // if it is present in phrase then reveal
// then reveal that letter

1 个答案:

答案 0 :(得分:4)

是,不是。字符串是不可变的,因此您实际上无法更改它们。通常,您要做的是使用新字符进行复制。像这样。

public String replace( String s, char c, int index ) {
  return s.substring( 0, index ) + c + s.substring( index+1, s.length() );
}

尽管需要进行错误(范围)检查。

不过,可能更好的方法是使用StringBuilder,它基本上是可变字符串。

public String replace( String s, char c, int index ) {
  StringBuilder sb = new StringBuilder( s );
  sb.setCharAt( index, c );
  return sb.toString();
}
相关问题