替换一个字符串。

时间:2014-04-07 17:40:21

标签: java string replace char

我已经替换了一个字符串,所有字母都显示为**但是当我要求用户输入字符时,我似乎无法将字母从*转换回字符串。我将在下面向您展示我在代码中所做的事情:

    System.out.println(randomPirateWord.replaceAll("\\S", "*"));
    System.out.println("guess a letter");
    char letterGuesed = input.findInLine(".").charAt(0);
    System.out.println(randomPirateWord.replaceAll("\\S"+letterGuesed,"*")); 

3 个答案:

答案 0 :(得分:1)

方法replaceAll的工作方向相反。首先是一个正则表达式,接下来是匹配的替换,所以你用'*'替换猜测的字母,这与你想要实现的相反。

答案 1 :(得分:0)

我会使用保存String的{​​{1}},而在另一个函数中只显示hiddenWord s中字符串的长度,然后将*letterGuessed进行比较hiddenWord并将*更改回hiddenWord

答案 2 :(得分:0)

也许不是replace all,但这似乎有效:

import java.util.Scanner;
class hola{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        String randomPirateWord = "HelloWorld";
        System.out.println("");
        boolean notComplete = true;
        char words[] = new char[randomPirateWord.length()];
        char words2[] = new char[randomPirateWord.length()];
        for(int i = 0; i < randomPirateWord.length(); i++){
            words[i] = randomPirateWord.charAt(i);
            words2[i] = '*';
        }
        while(notComplete){
            System.out.print("Type a letter: ");
            char letter = sc.next().charAt(0);
            notComplete = false;
            for(int i = 0; i < randomPirateWord.length(); i++){
                if(words[i] == letter){
                    words2[i] = letter;
                }
            }
            for(int i = 0; i < randomPirateWord.length(); i++){
                System.out.print(words2[i]);
            }
            for(int k = 0; k < randomPirateWord.length(); k++){
                if(words2[k] == '*'){
                    notComplete = true;
                    break;
                }
            }
            System.out.println("");
        }
    }
}