javareplaceletters

I'm stuck on "3.8.12: Replace Letter" in Java on CodeHS


The instructions are to:

Write a method that replaces all instance of one letter with another.

For example,

replaceLetter("hello", 'l', 'y')

returns

"heyyo"

I'm not even sure where to start but I've got this so far:

String str = "Hello world";
System.out.println (str);
str = str.replace("l", "y");
System.out.println (str);

But I have to get my actual method to look like this:

public String replaceLetter(String word, char letterToReplace, char replacingLetter)

so inputing any string would work, not just "Hello world" which I used as a test.


Solution

  • The method would look like this:

    public static String replaceLetter (String word, char original, char newChar) {
        return word.replace(original, newChar);
    }