我正在进行 Java CodeBat 练习。 Here is the one I am stuck on :
Look for patterns like "zip" and "zap" in the string -- length-3, starting with 'z' and ending with 'p'. Return a string where for all such words, the middle letter is gone, so "zipXzap" yields "zpXzp".
这是我的代码:
public String zipZap(String str){
String s = ""; //Initialising return string
String diff = " " + str + " "; //Ensuring no out of bounds exceptions occur
for (int i = 1; i < diff.length()-1; i++) {
if (diff.charAt(i-1) != 'z' &&
diff.charAt(i+1) != 'p') {
s += diff.charAt(i);
}
}
return s;
}
这对其中一些人来说是成功的,但对其他人来说则不然。对于某些示例字符串,&&
运算符的作用类似于 ||
;也就是说,很多我想保留的角色都没有保留。我不确定如何修复它。
如果您愿意的话,请朝正确的方向轻推!我只需要一个提示!
最佳答案
事实上恰恰相反。你应该这样做:
if (diff.charAt(i-1) != 'z' || diff.charAt(i+1) != 'p') {
s += diff.charAt(i);
}
这相当于:
if (!(diff.charAt(i-1) == 'z' && diff.charAt(i+1) == 'p')) {
s += diff.charAt(i);
}
关于java - 返回减去特定字符之间的特定字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29497184/