簡體   English   中英

字符串內的字符串遞歸函數錯誤

[英]String within a string recursive function error

我要編寫的遞歸函數有問題。 該函數的目的是在字符串中找到一個字符串,然后使用遞歸返回第二個字符串位於第一個字符串內的索引。

我能夠做到這一點。 當第二個字符串不包含在第一個字符串中時,就會出現問題。 我想向用戶表明找不到第二個字符串。 我無法中繼該消息。

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

任何幫助將不勝感激! :)

如果第一個字符串不包含第二個字符串,則index將無限遞增,使string s長度為零。 因此,您必須檢查第一個字符串是否短於第二個字符串。 如果是這樣,則不包含子字符串。

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

但是您根本不應該在這里使用遞歸函數。 也有一個內置的功能findstring :檢查這個問題: 檢查是否字符串包含在C ++字符串

首先,最重要的是,由於您未在index_of定義index ,因此您發布的代碼中有很多問題將無法編譯。 當然,僅當兩個字符串長度相同時才進行比較。 但是由於要根據未定義的變量index獲取子字符串,因此很難弄清楚您要進行的比較是什么; 如果index0 ,則獲取子字符串是沒有意義的;如果index不為0 ,則s.substr( index, len2 ) == t永遠不可能為真(因為只有當ss都進入該分支時, t具有相同的長度。

您真正要做的就是以簡單的英語定義函數應該做什么:

  • 如果s小於t ,則不可能匹配,因此返回-1。

  • 否則,如果s的開頭等於t ,則返回當前索引。

  • 否則,您將遞歸s的子字符串,刪除第一個字符(並遞增index )。

當然,您還需要在某處維護index 在經典遞歸中,這將作為附加函數參數。

坦白說,我不會構造所有這些子字符串。 在C ++中,使用迭代器更為慣用。 而且我會將遞歸函數包裝在一個非遞歸函數中,以便用戶不必傳遞任何其他參數:用戶可以調用類似以下內容的方法:

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

或者,不通過額外的參數:

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

(我假設這是家庭作業;通常不會對此類問題使用遞歸。否則,當然,只需在第二個版本中調用std::search完成工作。或text.find( target ) ,它幾乎完全返回您想要的內容。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM