[Solved] Write a method that will remove all the occurrences of the substring “rawr” [closed]


Problem is that after removing “rawr” you move to next position in String ignoring fact that your String have changed and need to be checked again at the same position.

Take a look

>xxxrawrrawrawr
    ^we are here now and we will remove "rawr" 
     so we will get
>xxxrawrawr
    ^do we want to move to next position, or should we check again our string?

Try maybe this way:

public static String noRawr(String str) // 7
{
    String result = str;

    for (int i = 0; i < result.length() - 3; ) {// I move i++ from here
        if (result.substring(i, i + 4).equals("rawr")) {
            result = result.substring(0, i) + result.substring(i + 4);
        }else{
            i++; //and place it here, to move to next position 
                 //only if there wont be any changes in string
        }
    }
    return result;
}

Test:

public static void main(String[] args) {
    String[] data = {"hellorawrbye","rawrxxx","xxxrawr","rrawrun","rawrxxxrawrrawrawr"};
    for (String s : data) {
        System.out.println(s+ " -> " + noRawr(s));
    }
}

Output:

hellorawrbye -> hellobye
rawrxxx -> xxx
xxxrawr -> xxx
rrawrun -> run
rawrxxxrawrrawrawr -> xxxawr

2

solved Write a method that will remove all the occurrences of the substring “rawr” [closed]