我在CodingBat.com上練習Java,並且遇到問題。for循環到達字符串的末尾
zipZap(「azbcpzpp」)返回「azbcpzpp」。有望重返 「azbcpzp」
感謝
// http://codingbat.com/prob/p180759
// 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) {
if (str.length() < 2)
return str;
String result = str.substring(0, 1);
for (int i=1; i < (str.length()-1) ; i++) {
if ((str.charAt(i-i) != 'z') || (str.charAt(i+1) != 'p'))
result += str.charAt(i);
}
result += str.substring(str.length()-1);
return result;
}
你也可以嘗試使用正則表達式。 '/ z \ wp/gi' –