您将如何设置嵌套循环以针对每次出现的模式搜索字符序列?到目前为止,这是我所拥有的,但是它只显示一个事件并给出indexoutofbounds错误。我该如何解决?
int i = 0;
while (i < data.size()) {
if (patternString.charAt(0) == data.get(i)) {
i++;
int j = 0;
while (patternString.charAt(j) == data.get(i)) {
j++;
System.out.println(j) ;
if (j == patternString.length()) {
System.out.println("Found pattern " + "at index " + (i));
}
}
} else { i++;}
}
答案 0 :(得分:0)
您可以只使用String#indexOf
:
int index = 0;
while (index != -1) {
// this line replaces your code
index = data.indexOf(patternString, index);
// a result of -1 means pattern was not found
if (index != -1) {
System.out.printf("%s found at index %d%n", patternString, index);
}
}
答案 1 :(得分:0)
您很可能会收到IndexOutOfBounds错误,因为在访问i
和j
之前没有检查data
和patternString
是否在范围之内。
如上所述,还有更多简便的方法,但是,如果您仍然想“手动”进行模式搜索,则可以尝试以下方法:
int j = 0;
for (int i = 0; i < data.size(); i++) {
if (patternString.charAt(j) == data.get(i)) {
while (j < patternString.length() && i < data.size() && //indices checks
patternString.charAt(j) == data.get(i) ) {
j++;
i++;
}
if (j == patternString.length()) {
i -= patternString.length(); //set i back to the start of the pattern
System.out.println("Found pattern " + "at index " + (i));
}
j = 0;
}
}