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

标签 java string stringindexoutofbounds

我有以下任务要做:

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;

关于Java 如何避免字符串索引越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52073708/

相关文章:

java - Java中聚合和组合的实现区别

java - 如何在 Java 中搜索两个字符串之间的值范围

linux - 如何计算单词在磁盘上所在位置的 block 号?

r - 按组填写字符列中的缺失值(nacof/nocb)

Kotlin:运行长度编码

r - R编程中的下标越界错误

java - 为什么我得到这个 NullPointerException?

java - 在 Spring 中使用加密的属性文件

android - 转换从 Android 中的 BufferedReader 读取的 char[] 时出现 StringIndexOutOfBoundsException

java - 编译引用类构造函数的Maven编译错误