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