2012-09-06 39 views
3

所以基本上,用戶輸入2串(CATSATONTHEMAT AT),我們需要計算第二個字符串多少時間出現在第一個字符串中(所以這裏的答案是3)比較子串來串在Java中

這是我迄今爲止,並口口聲聲說

「在線程異常‘主要’java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:81223 在java.lang.String.substring(來源不明) 在practice.main(practice.java:60)」

任何幫助,將不勝感激!我只是不明白找我哪裏錯了

String s = scan.next(); // CATSATONTHEMAT 
    String t = scan.next(); // AT 

    int j= 0; 

    for (int i = 0 ; i < s.length(); i++){ 
     int k = t.length(); 
     String newstring = s.substring(i,i+k); // I printed this and the substring works so the if statement might not be working.. 

     if(newstring.equals(t)) 
      j++; // if the new substring equal "AT" then add 1 
     } 

    System.out.printf("%d", j); // suppose to print just 3 
+0

看起來像一個典型的面試問題!你有沒有考慮使用'String.indexOf(字符串str,詮釋的fromIndex)'?在現實世界中你只使用來自[公地郎(http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/StringUtils.html)StringUtils.countMatches()! –

回答

3

的outOfBounds發生異常時,當我靠近年代末和K帶你傳遞的字符串的結尾。

您需要更改的循環只上升到s.length() - t.length()

for (int i = 0 ; i < s.length()-t.length(); i++){ 

我也建議使INT K = t.length()出來的for循環。您不需要爲每次迭代分配該值,因爲每次迭代都應該相同。

+0

謝謝!我沒有考慮到子字符串會超出循環!我替換了邊界並添加了一個+1,因爲s.length() - t.length()會取出2個空格,我仍然需要檢查這兩個是否可以成爲第二個字符串的一部分。我嘗試了不同的例子,它似乎工作得很好。再次謝謝你! – user1653266

0

IndexOutOfBoundsException異常發生 如果將beginIndex爲負,或者
endIndex大於此String對象的長度長,

或beginIndex大於endIndex。

在下面的行中,當循環運行從0到s.length ,但它應該從0運行到s.length-t.length。

String newstring = s.substring(i,i+k);