[英]C++ recursion scanning with strings
我有一个正在使用递归的作业。 我仍然在理解递归或至少是如何工作方面有一些麻烦,但是我不确定是否有任何工作原理,但我想我已经开始掌握它了。
我的作业分为两部分,但目前,我只需要对第一部分有所帮助。 这是我要做的:
编写一个递归函数,该函数将返回C字符串中>字符首次出现的位置
这是我到目前为止所拥有的...
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
int test(string s, char x);
int main ()
{
test("lets test for the letter s", "s" );
}
int test(string s, char x)
{
if(s.length() == 0)
return 0;
else if (s[0] == x)
return 1 + test(s.substr(1, s.length()), x);
else
return test(s.substr(1, s.length()), x);
}
因此,我认为这应该可行,但是对于如何使函数进行任何测试,我有些困惑。 我很确定我在main的函数调用中正确完成了字符串部分,但是我无法让char接受值。 以我的理解方式,我应该输入要扫描的文本,然后输入要查找的字符。 谁能告诉我我做错了什么,甚至我甚至不熟悉递归函数?
您应该执行以下操作:
int main ()
{
test("lets test for the letter s", 's');
//should pass char constant
//not string literal for second parameter
}
int test(string s, char x)
{
if(s.length() == 0)
return 0;
else if (s[0] == x)
return 1 + test(s.substr(1, s.length()-1), x);
//^^^second parameter of substring is length
else
return test(s.substr(1, s.length()), x);
}
字符常量用单引号引起来。 要测试您的功能,请编写类似以下内容的代码:
cout << test("lets test for the letter s", 's') << endl;
至于递归函数,您将关闭。 if
语句具有正确的测试,您只需要稍微调整return
语句即可。
if (s.length() == 0)
return -1;
如果字符串为空,则找不到该字符。 我建议返回-1而不是0,因为返回值0暗示(对我而言)该字符位于位置0。-1是找不到字符时此类函数的传统返回码。
else if (s[0] == x)
return 0;
您知道为什么return 0
吗? 您在索引0处找到了字符x
,因此应返回: 0
!
else
return 1 + test(s.substr(1, s.length() - 1), x);
最后一个测试是唯一需要递归的测试。 这是放置1 +
。 而且您还需要将length()
减少1。
“ s”将被视为char数组或字符串。 要代表一个字符,您应该使用's'
int main ()
{
cout << "location = " << test("lets test for the letter s", 's' );
^^^^
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.