[英]Search string to find another string using recursion
我正在研究以下簡單程序:
/**
Recursively searches a string to find a second string.
@param s the string to search through.
@param t the string to search for
@return true if t is found in s.
Tests whether the string t is contained in a string s.
For instance, calling the function like this:
bool b = find("Mississippi", "sip");
returns true, since "sip" is contained in "Mississippi".
You must write this as a recursive function, not by just
calling the string::find() function, or by using a loop.
*/
bool find(const string& s, const string& t)
{
string temp = s;
if(temp.size() < t.size())
return false;
temp.erase(0, 1);
find(temp, t);
}
這是我的測試輸出:
Checking function: Checking the find recursive function. -------------
+ find("Mississipi", "ipi")
X find("Mississipi", "ipx") should be false, but is true.
+ find("Sommertown", "Som")
+ find("Sommertown", "Sommertowne")
+ find("Somewhere in the middle", "in")
----------------------------------------------------------------------
Tests passing 4/5 (80%).
我已經寫了大約4種其他方式,所有方式都類似...包括一種使用find(temp.substr(1),t)而不是temp.erase的方式。
有人介意將我指向正確的方向嗎? 我知道這是一個簡單的錯誤,但我沒有看到!
謝謝!
您的解決方案有兩個問題:
find
所有控制路徑都顯式返回值 t
絕不會與s
進行任何比較,因此find
實際上並不是在檢查t
它只是被刪除,一次刪除一個字符。 編寫函數的更好方法可能是這樣的:
bool find(const string& s, const string& t)
{
string temp = s;
// Boundary condition which should return true
if (temp.substr(0, t.size()) == t)
return true;
// Boundary condition which should return false
if (temp.size() < t.size())
return false;
return find(temp.substr(1), t); // Recursive call
}
^^請注意,在此函數中,所有可能的控制路徑都返回一個值,並且t
將始終與s
進行比較。
還要注意,我說過在您的解決方案中,並非所有控制路徑都明確地返回一個值。 即使您沒有return語句,C ++函數也將返回值,但是正如@Johan指出的那樣,這是最后評估的結果, 而不是正確的。 例如,我對您的解決方案進行了編碼,並從find
收到響應“ 224”,而如果find
返回true,則我將收到響應“ 1”-或true。
您的函數將始終返回false。 它的作用是刪除字符串s的一個字符,直到s.size()<t.size()。
我將通過以下方式編寫該函數:)
bool find( const std::string &s, const std::string &t )
{
return ( s.size() < t.size() ?
false :
( s.compare( 0, t.size(), t ) == 0 ?
true :
find( std::string( s, 1 ), t ) ) );
}
我弄清楚了伙計們:
bool find(const string& s, const string& t)
{
if(s.length() < t.length())
return false;
else if(s.substr(0, t.size()) == t)
return true;
return find(s.substr(1),t);
}
TESTING H37, loginID
----------------------------------------------------------------------
Checking function: Checking the find recursive function. -------------------
+ find("Mississipi", "ipi")
+ find("Mississipi", "ipx")
+ find("Sommertown", "Som")
+ find("Sommertown", "Sommertowne")
+ find("Somewhere in the middle", "in")
----------------------------------------------------------------------
Tests passing 5/5 (100%).
Press any key to continue . . .
感謝您的幫助! 這個網站是新程序員的天賜之物!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.