根据 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
,则返回原字符串不变。
关于Java String.replace() - 替换的不仅仅是我指定的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29391088/