简体   繁体   English

字符串内的字符串递归函数错误

[英]String within a string recursive function error

I have a problem with a recursive function I'm trying to write. 我要编写的递归函数有问题。 The purpose of the function is to find a string within a string and then return the index at which the second string is located inside the first using recursion. 该函数的目的是在字符串中找到一个字符串,然后使用递归返回第二个字符串位于第一个字符串内的索引。

I am able to do this. 我能够做到这一点。 The problem comes when the second string isn't contained in the first string. 当第二个字符串不包含在第一个字符串中时,就会出现问题。 I'm want to out to the user that the second string was not found. 我想向用户表明找不到第二个字符串。 I can't get it to relay that message. 我无法中继该消息。

int index_of(string s, string t){
  int len1 = s.length(), len2 = t.length(), index = 0;
  if (len1==len2){
     if (s.substr(index, len2) == t){
       return index;
     }else{
       return -1;
     }
  else{
    index++;
    return index_of(s.substr(index, len1),t)+index;
  }
}

int main(){ 
  string strOne = "", strTwo = "";
  cout << "This program will find the ocurrence of one string within        another.\n\nEnter the string to be searched:\t";
  getline(cin, strOne);
  cout << "\nNow enter the string you want to search for:\t";
  getline(cin, strTwo);
  int index = index_of(strOne, strTwo);
  if (index == -1){
    cout << "\nThe second string cannot be found. Sorry!\n\n";}
  else{
    cout << "\nThe index of the substring is:\t" << index << "\n\n";
  }
  system("PAUSE");
  return 0;
}

Any help would be greatly appreciated! 任何帮助将不胜感激! :) :)

If first string doesn't contain the second, index being incremented infinitely making string s zero length. 如果第一个字符串不包含第二个字符串,则index将无限递增,使string s长度为零。 So you have to check, whether the first string is shorter than the second. 因此,您必须检查第一个字符串是否短于第二个字符串。 If so, it doesn't contain the substring. 如果是这样,则不包含子字符串。

  if (len1 < len2){
    // first string doesn't contain the second
    return -2;
  }else if (len1==len2){
    ...

But you shouldn't use recursive function here at all. 但是您根本不应该在这里使用递归函数。 Also there is a built-in function find in string : Check this question: Check if a string contains a string in C++ 也有一个内置的功能findstring :检查这个问题: 检查是否字符串包含在C ++字符串

There are a number of problems in the code you've posted, first and formost, that it won't compile, because you don't define index in index_of . 首先,最重要的是,由于您未在index_of定义index ,因此您发布的代码中有很多问题将无法编译。 And of course, you only do the comparison whenthe two strings are the same length. 当然,仅当两个字符串长度相同时才进行比较。 But it's hard to figure out what the comparison is that you're trying to do, since you take a substring based on the undefined variable index ; 但是由于要根据未定义的变量index获取子字符串,因此很难弄清楚您要进行的比较是什么; if index is 0 , the there is no point in taking the substring, and if index isn't 0 , then s.substr( index, len2 ) == t can never be true (since you only enter this branch if both s and t have the same length. 如果index0 ,则获取子字符串是没有意义的;如果index不为0 ,则s.substr( index, len2 ) == t永远不可能为真(因为只有当ss都进入该分支时, t具有相同的长度。

What you really have to do is start by defining in plain English what the function should do: 您真正要做的就是以简单的英语定义函数应该做什么:

  • If s is shorter than t , no match is possible, so you return -1. 如果s小于t ,则不可能匹配,因此返回-1。

  • Otherwise, if the start of s is equal to t , you return the current index. 否则,如果s的开头等于t ,则返回当前索引。

  • Otherwise, you recurse on the substring of s , removing the first character (and incrementing index ). 否则,您将递归s的子字符串,删除第一个字符(并递增index )。

Of course, you also need to maintain index somewhere; 当然,您还需要在某处维护index in classical recursion, this would be as an additional function argument. 在经典递归中,这将作为附加函数参数。

Frankly, I would not construct all of those substrings. 坦白说,我不会构造所有这些子字符串。 It's far more idiomatic in C++ to use iterators. 在C ++中,使用迭代器更为惯用。 And I would wrap the recursive function in a non-recursive one, so that the user wouldn't have to pass in any extra arguments: the user might call something like: 而且我会将递归函数包装在一个非递归函数中,以便用户不必传递任何其他参数:用户可以调用类似以下内容的方法:

int
indexOf( std::string const& text, std::string const& target )
{
    return indexOf( 0, text.begin(), text.end(), target );
}

Or, without passing the extra argument: 或者,不通过额外的参数:

int
indexOf( std::string const& text, std::string const& target )
{
    std::string::const_iterator results 
            = search( text.begin(), text.end(), target );
    return results == text.end()
        ?  -1
        :  results - text.begin();
}

(I'm assuming that this is homework; one wouldn't normally use recursion for a problem like this. Otherwise, of course, just call std::search in the second version, and the job is done. Or text.find( target ) , which returns almost exactly what you want.) (我假设这是家庭作业;通常不会对此类问题使用递归。否则,当然,只需在第二个版本中调用std::search完成工作。或text.find( target ) ,它几乎完全返回您想要的内容。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM