在Java中将子字符串与字符串进行比较 [英] Comparing a Substring to a string in Java
问题描述
所以基本上,用户输入2个字符串(CATSATONTHEMAT AT),我们需要计算第二个字符串在第一个字符串中出现的次数(所以这里的答案是3)
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
线程中的异常mainjava.lang.StringIndexOutOfBoundsException:String index超出范围: 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)"
任何帮助将不胜感激!我只是看不到找到我错了的地方。
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
推荐答案
outOfBounds异常当我接近s的结束和k接受你通过字符串的结尾。
The outOfBounds exception happens when i is near the end of s and k takes you passed the end of the string.
你需要改变循环只到达s.length -t.length()
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++){
我也建议将int k = t.length for循环。您不需要指定每次迭代,因为每次迭代都应该是相同的。
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.
这篇关于在Java中将子字符串与字符串进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!