如何在字符序列中搜索模式?

时间:2018-10-09 09:04:56

标签: java

您将如何设置嵌套循环以针对每次出现的模式搜索字符序列?到目前为止,这是我所拥有的,但是它只显示一个事件并给出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++;} 
} 

2 个答案:

答案 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错误,因为在访问ij之前没有检查datapatternString是否在范围之内。

如上所述,还有更多简便的方法,但是,如果您仍然想“手动”进行模式搜索,则可以尝试以下方法:

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;
    } 
}