返回true,如果字符串“猫”和“狗”的出现给定的字符串中的相同的次数。遍历字符串数组
猫狗( “猫狗”)→真
猫狗( “catcat”)→假
猫狗( “1cat1cadodog”)→真
public boolean catDog(String str) {
int countCat=0;
int countDog=0;
for(int i=0;i<str.length()-3;i++){
if(str.substring(i).startsWith("cat")){
countCat++;
}
if(str.substring(i).startsWith("dog")){
countDog++;
}
}
if(countCat==countDog){
return true;
}
else{
return false;
}
}
我无法写这个方法。有人知道为什么我的代码无法正常工作吗? 编辑:代码编译,但它会给出错误的输出。例如,如果我把“猫狗”,它返回false。
你检查,你重复的次数正确的金额是多少?因为你目前没有。 – Tom
我明白了,我明白了。我正在使用子字符串(i,i + 3),并且在开始使用startsWith时忘记更改迭代步骤的长度。 – DerDieDasEhochWas