Java 具有良好效率的递归grep

Java 具有良好效率的递归grep,java,Java,这个问题对我来说非常具体,所以我找不到有关堆栈溢出的相关问题。所以,我正在编写一个grep,如下所示。我对StringIndexOutofBoundException感到困惑。原因是我正在检查它是否等于\0。这意味着我正在处理越界异常,不是吗 例如: grep("hello","llo"); 这将返回3。这是因为它在original[2]位置3开始匹配。但是,我遇到了索引外错误。我已经花了好几个小时,但我想不出来 public static int grep(String ori, Strin

这个问题对我来说非常具体,所以我找不到有关堆栈溢出的相关问题。所以,我正在编写一个grep,如下所示。我对
StringIndexOutofBoundException
感到困惑。原因是我正在检查它是否等于
\0
。这意味着我正在处理越界异常,不是吗

例如:

grep("hello","llo");
这将返回3。这是因为它在
original[2]
位置3开始匹配。但是,我遇到了索引外错误。我已经花了好几个小时,但我想不出来

public static int grep(String ori, String ma){
    int toReturn = 0;
    int oCounter = 0;
    int i = 0;
    while (i < ma.length()){
      if (ori.charAt(toReturn) == ma.charAt(i)){
        i++;
        if (ma.charAt(i) == '\0'){ // error on this line
          return toReturn;
        }
        toReturn++;
        if (ori.charAt(toReturn) == '\0'){ // and this line if i delete the section above.
          return -1;
        }

      } else {
        i = 0;
        toReturn++;
      }

    }
    return -1;
}
publicstaticintgrep(字符串ori,字符串ma){
int-toReturn=0;
int-oCounter=0;
int i=0;
而(i
您将获得StringIndexOutOfBoundsException,因为您在循环内部过早且错误的阶段增加了
i

检查0是C++的东西。java中的字符串未\0终止

您正在编写的内容已在String类中完成。有几种方法可用

System.out.println("hello".indexOf("llo"));
将打印2,因为它已找到并从索引2开始。如果出于某种原因不喜欢从0开始,请随意添加1

您还会问“这意味着我正在处理异常,不是吗?”。不,没有。异常是用一种称为try-catch语句的特殊语法处理的。例如:

try {
    // possibly more lines of code here
    do_something_that_might_cause_exception();
    // possibly more lines of code here
} catch (Exception e) {
    // something did indeed cause an exception, and the variable e holds information about. We can do "exceptional" handling here, but for now we print some information.
    e.printStackTrace();
}

我已经有一段时间没有使用java了,但是我很确定您没有像在c中那样显式地检查
'\0'
。您是否正在尝试为您描述的Grep编写递归算法?(我将其称为substring()…我认为grep将找到“ma”的所有实例,并将一个列表(可能是索引列表)返回到ori中)