[英]Learning recursion: How can I locate a substring index within a string without using find?
我有一個遞歸函數來查找字符串中子字符串的起始索引。 我正在學習使用遞歸,因此不允許使用find函數。 我相信我已經滿足了大部分條件。 該函數應該在字符串中找到正確的索引。 如果為空,則返回-1。
這是真正的問題。 如果我輸入字符串“nothing”並搜索“jax”,則不返回-1。 我不明白為什么。 有什么幫助嗎? 這是代碼:
用戶輸入字符串s和t傳遞到下面:
int index_of(string s, string t)
{
int start = 0;
int len2 = t.length();
int index = 0;
if (s == "")
{
return -1;
}
else if (s.substr(1).length() <= t.length())
{
return -1;
}
else if ( s.substr(start, len2) == t)
{
return index;
}
else
{
index ++;
return index + index_of(s.substr(1), t);
}
return -1;
}
有幾個問題 - 一些小問題,一些非常重要的問題。
你有兩個變量, start
和index
,表示“當前位置”,但是一個就足夠了。
index
只能是0或1.因此,當前編寫的方式,您可以輕松擺脫index
並完全start
。
重要說明:在最終遞歸期間,到達字符串的結尾時,將-1
返回到上一個遞歸調用。 然后,由於遞歸調用的方式,您添加1
並將其返回到上一個調用,依此類推。 最終返回的值是-1
加上字符串的長度。 這就是你得到奇怪結果的原因。
這種比較
if (s.substr(1).length() <= t.length())
沒有多大意義。
考慮到所有這些因素,這是一個改進版本:
#include <iostream>
#include <string>
int index_of(
const std::string &s,
const std::string &t,
const size_t index)
{
int len2 = t.length();
if ((s.length() - index) < t.length())
return -1;
else if (s.substr(index,len2) == t)
return index;
else
return index_of(s,t,index + 1);
return -1;
}
/** Overloading, so you can call index_of with just
two arguments */
int index_of(const std::string &s, const std::string &t)
{
return index_of(s,t,0);
}
/** Some test cases. */
int main()
{
std::cout << index_of("hello","ello") << std::endl;
std::cout << index_of("nothing","jax") << std::endl;
std::cout << index_of("hello","llo") << std::endl;
std::cout << index_of("hello","lo") << std::endl;
std::cout << index_of("hello","o") << std::endl;
std::cout << index_of("hello","hel") << std::endl;
}
學習如何調試這樣的問題的最好方法是在紙上解決問題。 你的例子足夠小,不應該花太長時間。 這是很明顯,你會落入你的else
情況下,在最初的幾個步驟,因為字符串不匹配。 所以我們有:
index_of("nothing", "jax"):
index++; // index is now 1
return 1 + index_of("othing", "jax");
index_of("othing", "jax"):
index++; // index is now 1
return 1 + index_of("thing", "jax");
etc.
這有幫助嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.