-3

I'm new to Java and OOP. I'm currently studying for a class test and have the following question:

My task is to replace some characters in a given sentence by only using the length() and charAt() methods.

I was given the sentence:

"This is the letter i!"

this method:

public static String replaceCharacter(String w, char b, String v) { 
}

and the result should look like this:

"Theasts easts the letter east"

This is my starting point. I have no idea how to solve this one without using substring() method. Hope somebody can help me and give some explanation.

AtilioA
  • 419
  • 2
  • 6
  • 19
Mel Torment
  • 49
  • 1
  • 7

2 Answers2

0

Just loop through the String and if the charAt(i) is equal to your specific char, then append the replacement, otherwise append the charAt(i)

public static String replaceCharacter(String w, char b, String v) {
    String result = "";
    for (int i = 0; i < w.length(); i++) {
        if (w.charAt(i) == b) {
            result += v;
        } else {
            result += w.charAt(i);
        }
    }
    return result;
}

Demo

achAmháin
  • 4,176
  • 4
  • 17
  • 40
0

The trick is to remember that a String is essentially just an array of characters and if we want to change elements in an array, we can do that by using loops.

I'll assume that:

String w = "This is the letter i!";
char b = 'i';
String v = "east";

The method then is:

public static String replaceCharacter(String w, char b, String v) { 
    for (int i = 0; i < w.length(); i++) {
        if (w.charAt(i) != b) {
            // if the character is not 'i', we don't want to replace it
        } else {
            // otherwise, we want to replace it by "east"
        }
    }
}

Figuring out what code should go in the if and else block should be easy. Good luck!

Jasper
  • 66
  • 5