簡體   English   中英

我無法讓子串正常工作

[英]I am having trouble getting substring to work

該方法應該獲取某個模式的出現次數並返回int值。 我不斷收到這個錯誤

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

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()返回字符串的總長度,並且字符串的索引從0開始。因此,如果i等於字符串長度,則將超出范圍。 要解決此問題,請執行以下操作:

    i <= strand.length() - 1

要么

    i < strand.length()

當您指向的索引為null (不存在)時,出現StringIndexOutOfBoundsException 在這里,我看到的問題在strand.length()

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

這應該很好

您在String上迭代的次數過多。

對於substringcharAt或任何需要使用精確數值來獲得一個字符或一組字符的方法, String的大小定義為length()調用的結果減去1。

這就像一個數組(因為它由char[] ): "cat"長度為3,但是從零開始,所以我最多只能到2。

將您的條件更改為嚴格小於和小於或等於或等於。

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;
} 

(由於原因,將==更改為.equals 。請參閱本文 )如果不區分大小寫,請使用equalIgnoreCase

在其余答案中已經描述了length()

==測試引用相等性。

.equals()測試值是否相等。

如何在Java中比較字符串

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

length()返回數組中元素的數量。 永遠記住索引從0開始。因此,如果length為5,則有5個元素0、1、2、3和4。因此,必須使用i<strand.length();

您會得到StringIndexOutOfBoundsException因為索引為“ length-1”的元素是最后一個元素,並且您正在嘗試訪問索引為“ length”的元素。

3個問題...

在循環中將<=更改為<。

您還需要限制子字符串的右側不超過字符串的結尾。

而且您需要使用.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;
}  

您需要更正循環中的條件檢查,並在循環塊內添加新的檢查:

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;
}

也可以在循環條件本身中處理新添加的檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM