代码应该这样做:返回给定字符串中任何位置出现字符串“code”的次数,除非我们接受任何字母作为'd',所以“应付”和“cooe”数。太多例外越界 - JAVA
问题:java.lang.StringIndexOutOfBoundsException:跨异常冉字符串索引超出范围:11(行号:10)
public int countCode(String str){
int a = 0; // counter goes thru string
int b = str.length()-1;
int counter = 0; //counts code;
if(str.length() < 4) return 0;
else{
while (a <=b){
if(str.charAt(a) == 'c'){
if(str.charAt(a+1) == 'o'){
if(str.charAt(a+3) == 'e'){
counter++;
a= a+3;
} // checks e
else a++;
} // checks o
else a++;
} // checks c
else a++;
}
return counter;
}
}
这里就是我试图评估以得到所述例外:
- countCode( “xxcozeyycop”) - >预期的结果
- countCode( “cozcop”) - >预期的结果
见[此篇](http://stackoverflow.com/questions/2635082/java-counting-of-occurrences-of-a-word-in-a-string) – Benvorth 2014-10-05 13:51:40