如何用某个字母替换某个位置的字符

时间:2014-12-02 22:52:38

标签: java string loops replace character

我正在开发一个猜字游戏的程序,并且从数组列表中使用单词列表。我正在通过一种方法,用户将输入一个字符来猜测它是否在单词中。之后,程序告诉用户角色出现在" x"单词中的位置数(作为*****显示给用户)。我想现在替换" *****"在给定位置的角色。我知道程序必须扫描单词以及该字符所在的位置,它将替换" *"与角色。我怎么做?到目前为止,这就是我对这种方法的全部内容......

private static String modifyGuess(char inChar, String word,String currentGuess){
    int i = 0;
    String str = " ";
    while (i < word.length()){
        if(inChar ==  word.charAt(i)){

        }
        else{
            i++;
        }
    }
    return 
}

2 个答案:

答案 0 :(得分:2)

private static String modifyGuess(char inChar, String word, String currentGuess) {
    int i = 0;
    // I assume word is the original word; currentGuess is "********"
    StringBuilder sb = new StringBuilder(currentGuess);
    while (i < word.length()) {
        if (inChar ==  word.charAt(i)) {
            sb.setCharAt(i, inChar);
        }
        i++; // you should not put this line in the else part; otherwise it is an infinite loop
    }

    return sb.toString();
}

答案 1 :(得分:1)

您可以使用:

public String replace(String str, int index, char replace){     
    if(str==null){
        return str;
    }else if(index<0 || index>=str.length()){
        return str;
    }
    char[] chars = str.toCharArray();
    chars[index] = replace;
    return String.valueOf(chars);       
}

或者您可以使用 StringBuilder方法

 public static void replaceAll(StringBuilder builder, String from, String to)
{
    int index = builder.indexOf(from);
    while (index != -1)
    {
        builder.replace(index, index + from.length(), to);
        index += to.length(); // Move to the end of the replacement
        index = builder.indexOf(from, index);
    }
}
相关问题