返回一个字符串减去特定字符之间的特定字符

Returning a string minus a specific character between specific characters

我正在完成 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);
}

这听起来像是对正则表达式的完美使用。

正则表达式 "z.p" 将匹配任何以 z 开头、中间有任何字符并以 p 结尾的三个字母标记。如果您需要它是一个字母,您可以使用 "z[a-zA-Z]p" 代替。

所以你最终得到

public String zipZap(String str) {
    return str.replaceAll("z[a-zA-Z]p", "zp");
}

顺便说一句,这通过了所有测试。

你可以说这个问题是关于原始字符串操作的,但我认为这使这成为一个更好的教训:适当地应用正则表达式是一项非常有用的技能!

public String zipZap(String str) {
    //If bigger than 3, because obviously without 3 variables we just return the string.
    if (str.length() >= 3)
    {
      //Create a variable to return at the end.
      String ret = "";
      //This is a cheat I worked on to get the ending to work easier.
      //I noticed that it wouldn't add at the end, so I fixed it using this cheat.
      int minusAmt = 2;
      //The minus amount starts with 2, but can be changed to 0 when there is no instance of z-p.
      for (int i = 0; i < str.length() - minusAmt; i++)
      {
        //I thought this was a genius solution, so I suprised myself.
        if (str.charAt(i) == 'z' && str.charAt(i+2) == 'p')
        {
          //Add "zp" to the return string
          ret = ret + "zp";
          //As long as z-p occurs, we keep the minus amount at 2.
          minusAmt = 2;
          //Increment to skip over z-p.
          i += 2;
        }
        //If it isn't z-p, we do this.
        else
        {
          //Add the character
          ret = ret + str.charAt(i);
          //Make the minus amount 0, so that we can get the rest of the chars.
          minusAmt = 0;
        }
      }
      //return the string.
      return ret;
    }
    //If it was less than 3 chars, we return the string.
    else
    {
      return str;
    }
  }