[英]Return the number of times hi appears
I'm doing some coding bat exercises and I don't quite understand what's going on inside the for-loop. 我正在做一些编码蝙蝠练习,但我不太了解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;
}
Why is it str.length()-1? 为什么是str.length()-1? If I changed that to just str.Length I get an error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5 如果将其更改为str.Length,则会出现错误:线程“ main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:5
Think about this part: 想想这部分:
str.substring(i, i+2)
When i
is equal to the length of the string, i + 2
will overshoot the end of the string by 1, giving you an out of bounds error. 当i
等于字符串的长度时, i + 2
将使字符串的末尾超出1,从而出现超出范围的错误。
这是因为您在str.substring(i,i + 2)中使用了i + 2,这会导致超出范围的异常。
When you use str.length()
it gives you the length of the string, while the max index of string that is accessible is given by str.length() - 1
. 当您使用str.length()
它将为您提供字符串的长度,而可访问的字符串的最大索引由str.length() - 1
。 For example, "String"
will have length of 6. So, when you try to do this str.substring(5 , (5+ 2))
it will try to access the index which is out of the bound and hence it throw the exception. 例如, "String"
长度为6。因此,当您尝试执行此str.substring(5 , (5+ 2))
,它将尝试访问超出范围的索引,因此将抛出例外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.