Comparing a Substring to a string in Java

旧街凉风 提交于 2019-12-12 16:12:50

问题


so basically, a user inputs 2 strings ( CATSATONTHEMAT AT ) and we need to count how many time the second string appears in the first string ( so the answer here is 3 )

this is what I have so far, and it keeps saying

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

any help would be appreciated! I just can't see to find where I went 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

回答1:


The outOfBounds exception happens when i is near the end of s and k takes you passed the end of the string.

You need to change the loop to only go up to s.length()-t.length()

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

I would also recommend bringing the int k = t.length() out of the for loop. You don't need to assign that every iteration as it should be the same for every iteration.




回答2:


I think you would be better off using regular expressions. Take a look at this tutorial for hints: http://docs.oracle.com/javase/tutorial/essential/regex/matcher.html




回答3:


IndexOutOfBoundsException occurs if the beginIndex is negative, or
endIndex is larger than the length of this String object,

or beginIndex is larger than endIndex.

In the line below this problem occurs as loop is running from 0 to s.length but it should run from 0 to s.length-t.length.

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


来源:https://stackoverflow.com/questions/12309109/comparing-a-substring-to-a-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!