Java 如何避免字符串索引越界

Java How to avoid String Index out of Bounds

我有以下任务要做:

Return true if the string "cat" and "dog" appear the same number of times in the given string.

catDog("catdog") → true catDog("catcat") → false catDog("1cat1cadodog") → true

我的代码:

public boolean catDog(String str) {
int catC = 0;
int dogC = 0;
if(str.length() < 3) return true;
for(int i = 0; i < str.length(); i++){
   if(str.charAt(i) == 'd' && str.charAt(i+1) == 'o' && str.charAt(i+2)  == 'g'){
     dogC++;
   }else if(str.charAt(i) == 'c' && str.charAt(i+1) == 'a' && 
                                       str.charAt(i+2) == 't'){
    catC++;
  }
}

if(catC == dogC) return true;
return false;
}

但是 catDog("catxdogxdogxca")false 我得到 StringIndexOutOfBoundsException。我知道这是由 if 子句引起的,当它试图检查 charAt(i+2) 是否等于 t 时。我怎样才能避免这种情况? 谢谢你的问候:)

for(int i = 0; i < str.length(); i++){ // you problem lies here
   if(str.charAt(i) == 'd' && str.charAt(i+1) == 'o' && str.charAt(i+2)  == 'g')

您正在使用 i < str.length() 作为 循环终止条件 但您正在使用 str.charAt(i+1)str.charAt(i+2)

既然你需要访问i+2,那么你应该用i < str.length() - 2来限制范围。

for(int i = 0, len = str.length - 2; i < len; i++) 
// avoid calculating each time by using len in initialising phase;

逻辑有问题,条件语句试图访问超出字符串大小的字符。

输入:catxdogxdogxca 末尾有 ca 这就是执行 else 块的原因并且它试图让输入中不存在的字符出现在 i+3 处。这就是为什么您会看到 java.lang.StringIndexOutOfBoundsException.