代碼應該這樣做:返回給定字符串中任何位置出現字符串「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