gpt4 book ai didi

c - 如何在 C 中递归地查找另一个字符串中的字符串位置?

转载 作者:行者123 更新时间:2023-12-02 08:35:34 25 4
gpt4 key购买 nike

我们有一个创建带有两个字符串参数的递归函数的赋值,原型(prototype)应该如下所示:

int instring(char* word, char* sentence);

如果我们调用函数:

instring("Word", "Another Word"); 

它应该有以下返回值:

  • 如果找到该词,它将返回它找到该词的位置
  • 如果找不到该词,它将返回 -1

我可以用第三个参数来保存位置,但不幸的是我们不允许使用超过 2 个参数。

所以问题是我如何让它发挥作用?到目前为止,这是我想出的:

int instring(char* word, char* sentence) {
if (*word == '\0') {
return 0;
} else if (*word != '\0' && *sentence == '\0') {
return -1;
} else {
if (*word == *sentence) {
instring(word+1, sentence+1);
} else {
instring(word, sentence+1);
}
}
}

如果可以找到“单词”,我得到 0,否则我得到 -1。由于我无法跨函数调用存储任何值,因此我无法获取“word”字符串开始的位置。 除了外部变量和只有两个输入字符串之外,还有其他方法可以获取位置吗?

最佳答案

int instring( char* word, char* sentence ){
int lenw = strlen(word);
int lens = strlen(sentence);
if(lenw > lens) return -1;

if(strncmp(sentence, word, lenw)==0)
return 0;
else {
int ret = instring(word, sentence + 1);
if(ret < 0)
return ret;
return 1 + ret;
}
}

关于c - 如何在 C 中递归地查找另一个字符串中的字符串位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21947523/

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