2014-12-02 102 views
0

我想遞歸地計算出子內出現str內沒有子字符串重疊的次數。我所試圖做的是str.find(sub),如果它存在count++,然後返回計數+憶功能,但沒有找到位置:str.substr(str.find(sub) + sub.length())C++字符串遞歸substr

Here are some examples: 
subCcount("catcowcat", "cat") returns 2 
subCount("catcowcat", "cow") returns 1 
subCount("catcowcat", "dog") returns 0 

我試着寫代碼:

int count = 0; 
int subCount(const std::string& str, const std::string& sub) 
{ 
    int len = str.length(); 
    if(len == 0) 
    { 
     return 0; 
    } 
    else 
    { 
     if(str.find(sub) != string::npos) 
     { 
      count++; 
      return count + subCount(str.substr(str.find(sub) + sub.length()), sub); 
     } 
    } 
} 

測試的代碼:

X subCount( 「catcowcat」, 「貓」):預測[2],但發現[3]

X subCount(」 catcowcat」, 「牛」):預測[1]但發現[3]

「+ subCount( 「catcowcat」, 「狗」)

X subCount( 「cacatcowcat」, 「貓」):預期[2]但找到[9]

回答

0

你應該明確地使用調試器,並在尋求幫助之前檢查基本錯誤。

  • 在該函數的開始處將計數初始化爲零。
  • 添加一個else語句,返回if(str.find(sub)!= string :: npos)的計數值。

我希望這可以解決您的問題。

+0

非常感謝。如果Scite有調試器,我會節省很多時間。 – YoYo 2014-12-02 23:32:54