我正在学习Java CodeBat练习。这是我被困住的那个
查找字符串中的"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;
}这对他们中的少数人来说是成功的,但对其他人则不然。对于一些示例字符串,&&操作符似乎是一个||;也就是说,我想保留的许多字符都没有保留。我不知道该怎么办才能修好它。
如果你愿意的话,往正确的方向推一推!我只需要一点提示!
发布于 2015-04-07 17:12:08
事实上,情况正好相反。你应该这样做:
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);
}发布于 2015-04-07 17:14:38
这听起来像是正则表达式的完美使用。
regex "z.p"将匹配以z开头的任意三个字母标记,中间有任何字符,以p结尾。如果您要求它是一个字母,则可以使用"z[a-zA-Z]p"。
所以你最后
public String zipZap(String str) {
return str.replaceAll("z[a-zA-Z]p", "zp");
}顺便说一下,这通过了所有的测试。
您可以提出这个问题是关于原始字符串操作的论点,但我认为这是一个更好的教训:适当地应用regexes是一项非常有用的技能!
发布于 2016-12-15 05:04:27
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;
}
}https://stackoverflow.com/questions/29497184
复制相似问题