我正在尝试在第二个字符串中找到word
(在这种情况下为"abc"
)的所有排列。但我得到了StringOutOFBoundException
。代码有什么问题?
public class StringPermutations {
public static void main(String[] args){
int count = findPermutations("abc", "Helloabcwwwabcwwqqqqqqaawwbcwwwwabcabc");
System.out.println("The number of the permutations of abc is " + count);
}
public static int findPermutations(String word, String longString){
int count = 0;
int length = word.length();
String myString = "";
for(int i = 0; i < longString.length() - length; i++){
if(longString.substring(i, longString.length() - length - i).equals(word)){
count++;
}
}
return count;
}
}
答案 0 :(得分:0)
在你的循环中,substring的第二个参数有时是负数。您希望它为longString.substring(i, i + length)
答案 1 :(得分:0)
String.substring方法的参数不能为负数。 你应该改变de loop条件。
for(int i = 0; i <= longString.length() - length; i++){
if(longString.substring(i, i + length).equals(word)){
count++;
}
}
答案 2 :(得分:0)
for(int i = 0; i < longString.length() - length + 1; i++){
if(longString.substring(i, length + i).equals(word)){
count++;
}
}
循环长度应为longString.length() - length + 1
,
和substring (i, length + i)
。