代码之家  ›  专栏  ›  技术社区  ›  Riz

如何使用replace和charAt方法替换java字符串中多次出现的字符

  •  0
  • Riz  · 技术社区  · 8 年前

    这是我的第二个问题,还是个初学者,请耐心听我说。
    我有一个非常基本的刽子手类型游戏的代码。我已将字符更改为“-”,我可以获得输入的索引,但无法将“-”转换回输入的字符。
    这是一个不完整的代码。

        String input;
       String encrypt =  line.replaceAll("[^ ]","-");
       System.out.println(encrypt);
    
       for (int j=0;j<10;j++){ //Asks 10 times for user input
          input = inpscanner.nextLine();
          int check = line.indexOf(input);
          while (check>=0){
              //System.out.println(check);
              System.out.println(encrypt.replaceAll("-",input).charAt(check));
              check = line.indexOf(input,check+1);
          }
    

    下面是它的样子:
    你有10次机会猜到这部电影
    ------
    o
    o
    o
    L
    L
    你//不要重复,因为你不在电影里。而“o”是2倍。
    我想这样 loo--- (活套)。
    我怎么能这样做 "[^ ]","-" 如果是变量?

    1 回复  |  直到 8 年前
        1
  •  0
  •   Anil Bachola    8 年前

    这可能会有所帮助。

    public static void main(String[] args) {
        String line = "xyzwrdxyrs";
        String input;
        String encrypt =  line.replaceAll("[^ ]","-");
        System.out.println(encrypt);
        System.out.println(line);
        Scanner scanner = new Scanner(System.in);
        for (int j=0;j<10;j++) { //Asks 10 times for user input
            input = scanner.nextLine();
            //int check = line.indexOf(input);
            int pos = -1;
            int startIndex = 0;
            //loop until you all positions of 'input' in 'line'
            while ((pos = line.indexOf(input,startIndex)) != -1) {
                //System.out.println(check);
                // you need to construct a new string using substring and replacing character at position
                encrypt = encrypt.substring(0, pos) + input + encrypt.substring(pos + 1);
                //check = line.indexOf(input, check + 1);
                startIndex = pos+1;//increment the startIndex,so we will start searching from next character
            }
            System.out.println(encrypt);
        }
    }