0

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.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
Alyssa
  • 25
  • 2
  • 3
  • 8

3 Answers3

0

So you will want to take parameters and perform the actions that you did in your example code with "Hello world" on them. So everywhere in your code where you have "Hello world" instead put the word, since it is going to act as a place holder of what they put in to the method.

So for a simple example:

public void printMe(String wordToPrint){
    System.out.println(wordToPrint);
}

then if someone called it, it would look like this:

printMe("Hello, world"); //prints out "Hello, world"

Following this pattern you can then do that with all of the parameters in

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

As mentioned by others though, you are working in Java and not Javascript (based on the code you are posting).

Brett Fuller
  • 123
  • 6
0

The method would look like this:

public static String replaceLetter (String word, char original, char newChar) {
    return word.replace(original, newChar);
}
MaxxiBoi
  • 78
  • 1
  • 6
0

If you want to do it in simple and a straightforward way, Then you can Turn the String into a char[], iterate over the array, compare replace all the later by index, then convert the array back to string and return it.

Example

public static String replaceLetter (String word, char letterToReplace, char replacingLetter) {
    char[] wordChar = word.toCharArray();
    for (int i = 0; i < wordChar.length; i++) {
        if (wordChar[i] == letterToReplace) {
            wordChar[i] = replacingLetter;
        }
    }
    return String.valueOf(wordChar);
}
rimonmostafiz
  • 1,341
  • 1
  • 15
  • 33