1

As per this CodingBat problem I am trying to do the following:

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

My code:

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

This code replaces ALL the x characters in the string, rather than just the first and last. Why does this happen, and what would be a good way to solve it?

4

3 回答 3

4

你可以使用string.replaceAll函数。

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

上面的代码将替换x开头或结尾的代码。如果x开头或结尾没有,它将返回原始字符串不变。

于 2015-04-01T12:41:25.400 回答
1

replace方法的sdk:

返回一个新字符串,该字符串是用 newChar 替换此字符串中所有出现的 oldChar 所产生的。

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

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;
}
于 2015-04-01T12:44:11.210 回答
-1

您可以将 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;
    }
于 2015-04-01T14:24:44.093 回答