![](/img/trans.png)
[英]Return the number of times that the string “hi” appears anywhere in the given string
[英]Return the number of times hi appears
我正在做一些編碼蝙蝠練習,但我不太了解for循環中發生了什么。
public static int countHi(String str){
int count = 0;
// While i is less than the length of string increase the index by one
// Checking the char at each index
for(int i = 0; i < str.length()-1; i++){
// Do i + 2 because hi has two letters
// i = index 0 and add 2 so 0,1,2-- but 2 is exlcuded so check to see if index 0,1 equals "hi"
if(str.substring(i, i+2).equals("hi")){
count++;
}
}
System.out.println("Hi appears: " + count + " times.");
return count;
}
為什么是str.length()-1? 如果將其更改為str.Length,則會出現錯誤:線程“ main”中的異常java.lang.StringIndexOutOfBoundsException:字符串索引超出范圍:5
想想這部分:
str.substring(i, i+2)
當i
等於字符串的長度時, i + 2
將使字符串的末尾超出1,從而出現超出范圍的錯誤。
這是因為您在str.substring(i,i + 2)中使用了i + 2,這會導致超出范圍的異常。
當您使用str.length()
它將為您提供字符串的長度,而可訪問的字符串的最大索引由str.length() - 1
。 例如, "String"
長度為6。因此,當您嘗試執行此str.substring(5 , (5+ 2))
,它將嘗試訪問超出范圍的索引,因此將拋出例外。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.