基本上,用户输入了两个字符串(CATSATONTHEMAT和AT),我们需要计算第二个字符串在第一个字符串中出现的次数(因此这里的答案是3)。
目前为止这就是我的代码,但它一直显示:
“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)"
任何帮助将不胜感激!我只是找不到哪里出错了。
目前为止这就是我的代码,但它一直显示:
“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)"
任何帮助将不胜感激!我只是找不到哪里出错了。
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
String.indexOf(String str, int fromIndex)
吗?在现实世界中,你只需要使用commons-lang中的StringUtils.countMatches()! - James Bassett