简体   繁体   English

返回hi出现的次数

[英]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.

相关问题 返回字符串“hi”出现在给定字符串中的任何位置的次数 - Return the number of times that the string “hi” appears anywhere in the given string 需要找到字符串中最频繁出现的字符并返回出现的次数 - Need to find the character most frequent in a string and return the number of times it appears 返回字符串“ hello”出现在给定字符串中任何位置的次数 - Return the number of times that the string “hello” appears anywhere in the given string 返回字符串“code”在给定字符串中任何位置出现的次数 - Return the number of times that the string "code" appears anywhere in the given string 返回字符串“hello/HELLO/hello...”出现在给定字符串中任意位置的次数 - Return the number of times the string "hello/HELLO/hellO ..." appears anywhere in the given string 计算aaa在具有和重叠的字符串中出现的次数 - count number of times aaa appears in a string with and with overlaping Java:显示字母在字符串中出现的次数 - Java: display number of times a letter appears in a string 如何计算“。”在网页中出现的次数? - How to count the number of times “.” appears in a webpage? 该方法应该计算“.”、“?”或“!”的次数。 出现在文中 - the method is supposed to count the number of times a ‘.’, ‘?’, or ‘!” appears in the text 计算一个值出现的次数 - Count how many number of times a value appears
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM