gpt4 book ai didi

C++ 递归扫描字符串

转载 作者:行者123 更新时间:2023-11-28 00:47:04 24 4
gpt4 key购买 nike

我正在处理一项使用递归的作业。我在理解递归或至少它是如何工作的方面仍然有点困难,但我想我开始掌握它了,尽管我不太确定为什么一切都有效。

我的作业分为两部分,但目前,我只需要第一部分的一点帮助。这是我必须做的:

Write a recursive function that will return the position of the first occurence of a >character within a C String

这就是我目前所拥有的...

#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);
}

关于C++ 递归扫描字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15887161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com