比较子串来串在Java中

问题描述:

所以基本上,用户输入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()! –

的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

我想你会使用正则表达式会更好。看一看本教程的提示:http://docs.oracle.com/javase/tutorial/essential/regex/matcher.html

+0

感谢您分享,我会研究它 – user1653266

IndexOutOfBoundsException异常发生 如果将beginIndex为负,或者
endIndex大于此String对象的长度长,

或beginIndex大于endIndex。

在下面的行中,当循环运行从0到s.length ,但它应该从0运行到s.length-t.length。

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