编写一个方法,删除子串“rawr”的所有出现

时间:2013-06-05 23:27:06

标签: java

noRawr(“hellorawrbye”)“hellobye”, noRawr(“rawrxxx”)“xxx”,
noRawr(“xxxrawr”)“xxx”, noRawr(“rrawrun”)“跑”, noRawr(“rawrxxxrawrrawrawr”)“xxxawr”

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

    for (int i = 0; i < result.length() - 3; i++) {
       if (result.substring(i, i + 4).equals("rawr")) {
            result = result.substring(0, i) + result.substring(i + 4);
        }
    }
    return result;
}

1 个答案:

答案 0 :(得分:1)

问题是在删除“rawr”后你移动到String中的下一个位置,忽略你的String已经改变并需要在同一位置再次检查的事实。

看看

>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?

尝试这种方式:

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

测试:

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

输出:

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