lundi 31 août 2015

for loop gets to the end of the string

I'm practicing Java at CodingBat.com, and I have a problem.

zipZap("azbcpzpp") returns "azbcpzpp". Expected to return "azbcpzp"

Thanks

// http://ift.tt/1yb3m7N
// 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;
}

Aucun commentaire:

Enregistrer un commentaire