Hangman,如何在秘密字符串的正确位置替换字符串的下划线

时间:2015-04-09 10:28:36

标签: java algorithm

public class Test1 {

public static void main(String[] args) {
    String s = "ciao";
    String underscore = s.replaceAll(".", "_ ").trim();

    if (s.contains("a")){
        for (int i = 0; i< underscore.length(); i++){



        }
    }
    System.out.println(underscore);
}
}

您好如何在下划线的正确位置替换字符串“a”?我正在做一个HangMan游戏,所以我必须实现的算法不仅仅是这种情况。问题是我的下划线索引是不同的,格式是“_ _ _ _”必须是“ciao”但如果我只做一个猜测所以“a”..输出是“_ _ a _”

2 个答案:

答案 0 :(得分:4)

您应该保留字符串中每个字母位置的引用。 您可以使用toCharArray方法。

    String s = "ciao";
    String underscore = s.replaceAll(".", "_ ").trim();
    char[] sC = s.toCharArray();
    if(s.contains("a"){
      StringBuilder myUnderscore = new StringBuilder(underscore);
      for(int i = 0; i < sC.length; i++){
         if(sc[i] == 'a'){
           myUnderscore.setCharAt(i, 'a');
         }
      }
    }
    myUnderscore.toString();

希望它有所帮助,这是我的第一个答案!

答案 1 :(得分:0)

另一种方法,如果您不想使用StringBuilder类:

String s = "ciao";
String underscore = s.replaceAll(".", "_ ").trim();
System.out.println(underscore);

if (s.contains("a")) {
    char[] ca = underscore.toCharArray();
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) != 'a') {
            continue;
        }

        int j = i * 2;
        ca[j] = 'a';
    }

    // one way:
    underscore = String.valueOf(ca);

    // second way:
    // underscore = new String(ca);
}
System.out.println(underscore);

此解决方案计算字符数组sunderscore的字符位置。

参考文献: