Comparing substring with string in Java

so basically the user enters 2 lines (CATSATONTHEMAT AT), and we need to calculate how many times the second line appears in the first line (so the answer here is 3)

this is what I still have and he keeps talking

"Exception in thread" main "java.lang.StringIndexOutOfBoundsException: row index out of range: 81223 in java.lang.String.substring (Unknown source) in practice .main (practice.java:60)"

Any help would be appreciated! I just don’t see to find where I was wrong.

    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
+3
source share
3 answers

The outOfBounds exception occurs when I get closer to the end of s, and k passes you the end of the line.

, s.length() - t.length()

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

int k = t.length() for. , .

+3

IndexOutOfBoundsException beginIndex ,
endIndex String,

beginIndex , endIndex.

, 0 s.length 0 s.length-t.length.

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

All Articles