繁体   English   中英

Java如何避免字符串索引超出范围

[英]Java How to avoid String Index out of Bounds

我有以下任务要做:

如果字符串“ cat”和“ dog”在给定的字符串中出现相同的次数,则返回true。

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的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM