[英]C++ String Recursion substr
我試圖遞歸計算sub出現在str中的次數,而子字符串沒有重疊。 我正在嘗試做的是str.find(sub)
,如果它存在count++
,然后返回count +調用該函數但沒有找到位置: str.substr(str.find(sub) + sub.length())
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”,“ cat”):預期[2]但找到[3]
X subCount(“ catcowcat”,“ cow”):預期[1]但發現[3]
'+ subCount(“ catcowcat”,“ dog”)
X subCount(“ cacatcowcat”,“ cat”):預期[2]但發現[9]
在尋求幫助之前,您絕對應該使用調試器並檢查基本錯誤。
我希望這能解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.