评价我的(C++)代码:递归strstr sans任何标准库字符串函数:)

v_a*_*tia 0 c++ recursion

所以,这个想法是写一个递归函数,比较两个字符串,看看字符串'prefix'是否包含在字符串'other'中,不使用任何标准字符串函数,并使用指针算法.以下是我想出的.我认为它有效,但很奇怪 - 这是多么优雅,1-10级,你会做的任何明显的时髦动作呢?

谢谢.

bool is_prefixR(char* prefix, char* other) {
  static int prePos = 0,othPos = 0; 
  //  static int othPos = 0;
  bool test;
  test = ( *(prefix+prePos) == *(other+othPos)); //checks to see if same

  if (!*(prefix+prePos)) { return 1; } //end of recursion
  if (!*(other+othPos)) { return 0; }

  if (!test) {
    othPos++; //move othPos pointer by 1
    prePos = 0; //reset the prefix position
    return(is_prefixR(prefix, other)); //lets try again
  } else { //chars are the same
    othPos++; //move othPos pointer by 1
    prePos++;
    return(is_prefixR(prefix, other)); //lets try again
  }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

int*_*jay 11

  1. 这将无法在所有字符串上正常工作.例如:prefix ="aab",other ="aaab"

    • 不要使用静态变量.由于它们,第二次调用该函数将失败.

    • 不要使用递归:对于长字符串,您可以获得堆栈溢出.请改用循环.

    • 名称"prefix"用于出现在另一个字符串开头的字符串 - 这不是这里的情况.