Java String.replace() - 替换的不仅仅是我指定的子字符串?

Java String.replace() - replaces more than just the substring I specify?

根据 this CodingBat problem 我正在尝试执行以下操作:

Given a string, if the first or last chars are 'x', return the string without those 'x' chars, and otherwise return the string unchanged.

我的代码:

public String withoutX(String str) {
    if (str.startsWith("x")) {
        str = str.replace(str.substring(0, 1), "");
    }
    if (str.endsWith("x")) {
        str = str.replace(str.substring(str.length()-1), "");
    }
    return str;
}

此代码替换字符串中的所有 x 个字符,而不仅仅是第一个和最后一个。为什么会出现这种情况,有什么好的解决方法?

您可以使用 string.replaceAll 功能。

string.replaceAll("^x|x$", "");

以上代码将替换开头或结尾的 x。如果开头或结尾都没有x,那么return原字符串不变。

来自 replace 方法的 sdk:

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

无需替换即可解决此问题:

public String withoutX(String str) {   
    if (str == null) { 
        return null;
    }

    if (str.startsWith("x")) {
        str = str.substring(1);
    }
    if (str.endsWith("x")) {
        str = str.substring(0, str.length()-1);
    }

    return str;
}

您可以对第一个字符使用 replaceFirst,或者您可以在两边添加 1 个字符

public static String withoutX(String str) {
        if (str.startsWith("x")) {
            str = str.replaceFirst("x", "");
        }
        if (str.endsWith("x")) {
            str = str.substring(0,str.length() - 1);
        }

        return str;
    }