Michael
Michael

Reputation: 13

How to replace character at certain position with a certain letter

I am working on a program that is a word guessing game, and the list of words is used from an array list. I am working through a method where the user will input a character to guess if it is in the word. After that, the program tells the user the character appears in "x" number of positions in the word (that is displayed to the user as *****). I want to now replace the "*****" with the character at the given position. I know that the program has to scan through the word and where that character is, it will replace the "*" with the character. How do I do that? So far, this is all that I have for this method...

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 
}

Upvotes: 0

Views: 1980

Answers (2)

tianz
tianz

Reputation: 2183

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

Upvotes: 2

user4312749
user4312749

Reputation:

You can use this:

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

Or you can use the StringBuilder Method:

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

Upvotes: 1

Related Questions