簡體   English   中英

如何使用replace和charAt方法替換Java字符串中字符的多次出現

[英]How to replace multiple occurences of a character in a java string using replace and charAt methods

這是我的第二個問題,仍然是初學者,請耐心等待。
我有一個非常基本的子手類型游戲的代碼。我將字符更改為“-”,我能夠獲得輸入的索引,但無法將“-”轉換回輸入的字符。
它是不完整的代碼。

    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次猜電影的機會
------
Ø
Ø
Ø
大號
大號
u //不重復,因為u不在電影中,而'o'是2倍。
我想要像loo--- (looper)。
如果出現變量"[^ ]","-"我該如何處理"[^ ]","-"

這可能會有所幫助。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM