学习递归:如何在不使用find的情况下在字符串中找到子字符串索引?

时间:2012-03-15 14:44:20

标签: c++ recursion

我有一个递归函数来查找字符串中子字符串的起始索引。我正在学习使用递归,因此不允许使用find函数。我相信我已经满足了大部分条件。该函数应该在字符串中找到正确的索引。如果为空,则返回-1。

这是真正的问题。如果我输入字符串“nothing”并搜索“jax”,则不返回-1。我不明白为什么。有什么帮助吗?这是代码:

用户输入字符串s和t传递到下面:

int index_of(string s, string t)
{
    int start = 0;
    int len2 = t.length();
    int index = 0;

    if (s == "")
    {
        return -1;
    }
    else if (s.substr(1).length() <= t.length())
    {
        return -1;
    }
    else if ( s.substr(start, len2) == t)
    {
        return index;
    }
    else
    {
        index ++;
        return index + index_of(s.substr(1), t);
    }
    return -1;
}

2 个答案:

答案 0 :(得分:1)

有几个问题 - 一些是小问题,一些是非常重要的问题。

  1. 您有两个变量startindex来表示“当前位置”,但只有一个就足够了。

  2. index只能是0或1.因此,当前编写的方式,您可以轻松完全摆脱indexstart

  3. 重要提示:在最后一次递归期间,当到达字符串的结尾时,将-1返回到先前的递归调用。然后,由于递归调用的方式,您添加1并将其返回到上一个调用,依此类推。最终返回的值是-1加上字符串的长度。这就是你得到奇怪结果的原因。

  4. 此比较

    if (s.substr(1).length() <= t.length())
    

    没有多大意义。

  5. 考虑到所有这些因素,这是一个改进的版本:

    #include <iostream>
    #include <string>
    
    int index_of(
      const std::string &s,
      const std::string &t,
      const size_t index)
    {
      int len2  = t.length();
    
      if ((s.length() - index) < t.length())
        return -1;
      else if (s.substr(index,len2) == t)
        return index;
      else
        return index_of(s,t,index + 1);
      return -1;
    }
    
    /** Overloading, so you can call index_of with just
        two arguments */
    int index_of(const std::string &s, const std::string &t)
    {
      return index_of(s,t,0);
    }
    
    /** Some test cases. */
    int main()
    {
      std::cout << index_of("hello","ello") << std::endl;
      std::cout << index_of("nothing","jax") << std::endl;
      std::cout << index_of("hello","llo") << std::endl;
      std::cout << index_of("hello","lo") << std::endl;
      std::cout << index_of("hello","o") << std::endl;
      std::cout << index_of("hello","hel") << std::endl;
    }
    

答案 1 :(得分:1)

学习如何调试此类问题的最佳方法是将它们写在纸上。你的例子足够小,不应该花太长时间。很明显,在最初的几个步骤中你会陷入else的情况,因为字符串不匹配。所以我们有:

index_of("nothing", "jax"):
    index++;  // index is now 1
    return 1 + index_of("othing", "jax");
index_of("othing", "jax"):
    index++;  // index is now 1
    return 1 + index_of("thing", "jax");
etc.

这有帮助吗?

相关问题