Java替换特定字符

标签 java string replace

这是我在这个网站上的第一个问题,所以我会尽量不要成为一个十足的菜鸟..

我目前正在用java 创建刽子手游戏。 所以我问你的问题是我们是否被赋予了“幽灵”这个词 并将 Ghost 替换为“_”,

hiddenWord = ghost.length();
for (i=0; i < ghost.lenth(); i ++)
System.out.print("_ ")

给我们输出

“_ _ _ _ _”

假设我们猜字母“O” 字母“o”被猜到了,我该如何替换`

"_ _ _ _ _" with 
"_ _ o _ _ "

我当前的类文件

public void pickWord()
    {
        String[] listOfWords;
        listOfWords = new String[10];
        listOfWords[0] = "shenanigans";
        listOfWords[1] = "conversely";
        listOfWords[2] = "octopus";
        listOfWords[3] = "dizzy";
        listOfWords[4] = "malicious";
        listOfWords[5] = "goosebumps";
        listOfWords[6] = "flying";
        listOfWords[7] = "staff";
        listOfWords[8] = "xylophone";
        listOfWords[9] = "zapping";
        Random generator = new Random();
        int lineNumber = generator.nextInt(9);
        disguisedWord = listOfWords[lineNumber];


    }   
    public void displayMark()
    {
        for( int i = 0; i < disguisedWord.length(); i ++)
            underscore = underscore + "_ ";
        System.out.println(underscore);

    }
    public void makeGuess() throws IOException
    {
        System.out.println("Your word is " + disguisedWord.length() + " letters long.");
        System.out.println("Feel free to guess a letter.");
        guess = (char)System.in.read();

最佳答案

String ghost = "ghost";
String input = "o";
for (int i = 0; i < ghost.length(); i++) {
    if (String.valueOf(ghost.charAt(i)).equalsIgnoreCase(input)) {
        System.out.print(input + " ");
    } else {
        System.out.print("_ ");
    }
}

您可以使用三元运算符简化 if 语句:

System.out.print(String.valueOf(ghost.charAt(i)).equalsIgnoreCase(input) ? input + " " : "_ ");

关于Java替换特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13341581/

相关文章:

java - Avatar.js 和项目头像

arrays - 如何在golang中对数组中的字符串进行打乱?

C 返回字符串不正确

R 按行替换最小值的第一个实例

unix - 从目录中的所有文件名中删除下划线

java - 返回 HashMap 的值

java - ant-contrib 发布任务不起作用

java - java中的正则表达式

javascript - 如何创建一个 OnClick 函数,当用户单击一个单词时将其更改为另一个单词?

Java + Spring + hibernate : Dao implementation that is about to change in the future