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

时间:2015-04-07 17:08:07

标签: java string for-loop char charat

我正在进行Java CodeBat练习。 Here is the one I am stuck on

  

在字符串中查找“zip”和“zap”等模式 - 长度为3,以“z”开头,以“p”结尾。返回一个字符串,对于所有这些单词,中间字母不见了,所以“zipXzap”产生“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;
}

这对其中一些人来说是成功的,但对其他人则不然。对于某些示例字符串,似乎&&运算符的行为类似于||;也就是说,我想保留的许多角色都没有被保留。我不确定如何修复它。

如果你愿意的话,向正确的方向轻推!我只需要一个提示!

3 个答案:

答案 0 :(得分:2)

实际上它是另一种方式。你应该这样做:

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);
}

答案 1 :(得分:1)

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

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

所以你最终得到了

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

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

你可以提出这个问题是关于原始字符串操作的论点,但我认为这使得这更好的一课:正确应用正则表达式是一项非常有用的技能!

答案 2 :(得分:0)

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;
    }
  }
相关问题