2015-08-31 83 views
0

我在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; 
} 
+0

你也可以嘗試使用正則表達式。 '/ z \ wp/gi' –

回答

2

更改,如果條件if ((str.charAt(i - 1) != 'z') || (str.charAt(i + 1) != 'p'))。否則,你總是檢查索引0處的字符等於「Z」,因爲i-i始終爲0

public static 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 - 1) != 'z') || (str.charAt(i + 1) != 'p')) 
      result += str.charAt(i); 
    } 

    result += str.substring(str.length() - 1); 

    return result; 
} 

Input: azbcpzpp 
Output: azbcpzp 
+0

也應該是'&&'else匹配,如果連一個都是真的。 –

+0

這是一個非常好的捕獲... :) +1 – Codebender

相關問題