【问题标题】:is it possible to replace characters in a string with characters from another string?是否可以用另一个字符串中的字符替换字符串中的字符?
【发布时间】:2018-07-11 18:40:23
【问题描述】:

如果我有一个存储问题答案的字符串和一个用于用下划线隐藏答案的 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

【问题讨论】:

  • 这里有什么问题?我的意思是,String 是不可变的,所以你可能想要使用StringBuilder,但除此之外,我相信你可以处理这个。
  • 好吧,我正在尝试创建一个新字符串,该字符串将复制答案字符串,但会显示用户的猜测。例如,用户猜测 e,那么新字符串将打印出旧字符串,只是显示 e

标签: java string


【解决方案1】:

是和不是。字符串是不可变的,因此您实际上无法更改它们。你通常做的是用新角色制作副本。所以像这样。

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();
}

【讨论】:

  • 不错的建议。只需保留一个作为 StringBuilder 和 setCharAt 的 maskedAnswer 变量,只要显示一个字母即可。
  • 是的,OP 必须隐藏原始字符串,以便他们可以比较猜测,并向用户显示带有下划线的第二个字符串。他们还必须以某种方式考虑小写或大写字母(允许用户猜测“a”而不匹配大写“A”可能是不公平的),并且他们必须检测下划线何时出现字符串不再有下划线,游戏获胜。
猜你喜欢
  • 2021-06-15
  • 1970-01-01
  • 2019-05-14
  • 2016-02-04
  • 2021-12-04
  • 2011-02-21
  • 2013-12-03
  • 2017-01-28
  • 2017-03-07
相关资源
最近更新 更多