简体   繁体   English

我无法让子串正常工作

[英]I am having trouble getting substring to work

This method is supposed to get the number of occurrences of a certain pattern and return the int value. 该方法应该获取某个模式的出现次数并返回int值。 I keep getting this error 我不断收到这个错误

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1

Code

public int getCount(String pattern){
    int occerenceOfPattern = 0;
    for (int i = 0; i <= strand.length(); i++) {
        if (strand.substring(i, i + pattern.length()) == pattern) {
            occerenceOfPattern++;
        }
    }
    return occerenceOfPattern;
}   
    i <= strand.length()

.length() returns the total length of the string and the indexes of the string start at 0. So if i is equal to the string length you will get an out of bounds. .length()返回字符串的总长度,并且字符串的索引从0开始。因此,如果i等于字符串长度,则将超出范围。 To fix this use: 要解决此问题,请执行以下操作:

    i <= strand.length() - 1

or 要么

    i < strand.length()

StringIndexOutOfBoundsException comes when the index where you are pointing to is null (does not exist). 当您指向的索引为null (不存在)时,出现StringIndexOutOfBoundsException Here the problem I see is in strand.length() . 在这里,我看到的问题在strand.length()

for (int i = 0; i < strand.length(); i++)

This should work fine 这应该很好

You're iterating too far on your String . 您在String上迭代的次数过多。

For substring , charAt , or any method that requires to you to use an exact numerical value to get at a character or a group of characters, the size of the String is defined as the result of the length() call minus 1. 对于substringcharAt或任何需要使用精确数值来获得一个字符或一组字符的方法, String的大小定义为length()调用的结果减去1。

It's like an array (since it is backed by a char[] ): "cat" has length 3, but it's zero based, so I can only go up to 2. 这就像一个数组(因为它由char[] ): "cat"长度为3,但是从零开始,所以我最多只能到2。

Change your condition to be strictly less-than, and not less-than or equal to. 将您的条件更改为严格小于和小于或等于或等于。

public int getCount(String pattern){
    int occerenceOfPattern = 0;
    for (int i = 0; i < strand.length(); i++) {
        if (strand.substring(i, i + pattern.length()) .equals(pattern)) {
            occerenceOfPattern++;
        }
    }
    return occerenceOfPattern;
} 

(changed == to .equals . for reason see this post ) Use equalIgnoreCase if it is case insensitive. (由于原因,将==更改为.equals 。请参阅本文 )如果不区分大小写,请使用equalIgnoreCase

length() is already described in rest of the answers 在其余答案中已经描述了length()

== tests for reference equality. ==测试引用相等性。

.equals() tests for value equality. .equals()测试值是否相等。

How to compare Strings in java 如何在Java中比较字符串

i <= strand.length() in your for loop is your problem...

length() returns the number of elements in an Array. length()返回数组中元素的数量。 Always remember that index starts from 0. So, if length is 5, you have 5 elements 0,1,2,3 and 4. So, you have to use i<strand.length(); 永远记住索引从0开始。因此,如果length为5,则有5个元素0、1、2、3和4。因此,必须使用i<strand.length();

You get StringIndexOutOfBoundsException because element with index "length-1" is the last element and you are trying to access element with index="length". 您会得到StringIndexOutOfBoundsException因为索引为“ length-1”的元素是最后一个元素,并且您正在尝试访问索引为“ length”的元素。

3 problems... 3个问题...

Change <= to < in your loop. 在循环中将<=更改为<。

You also need to limit the right side of the substring to not be past the end of the string. 您还需要限制子字符串的右侧不超过字符串的结尾。

And you need to use .equals() not ==. 而且您需要使用.equals()而不是==。

public int getCount(String pattern){
    int occerenceOfPattern = 0;
    for (int i = 0; i < strand.length(); i++) {
        if (strand.substring(i, Math.min(i + pattern.length(), strand.length())).equals(pattern)) {
            occerenceOfPattern++;
        }
    }
    return occerenceOfPattern;
}  

You need to correct your condition check in loop and also add new check inside loop block: 您需要更正循环中的条件检查,并在循环块内添加新的检查:

public int getCount(String pattern){
    int occerenceOfPattern = 0;
    for (int i = 0; i < strand.length(); i++) { // Updated check
        if((i + pattern.length()) >= strand.length()) // New condition to avoid exception
            break;
        if (strand.substring(i, i + pattern.length()) == pattern) {
            occerenceOfPattern++;
        }
    }
    return occerenceOfPattern;
}

New added check can also be handled in loop condition itself. 也可以在循环条件本身中处理新添加的检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM