gpt4 book ai didi

c - 返回字符串中包含子字符串的第一个索引的递归函数

转载 作者:行者123 更新时间:2023-11-30 21:01:40 25 4
gpt4 key购买 nike

我需要创建一个递归函数,获取两个字符数组,并返回“subStr”出现在“str”中的第一个索引。

函数签名:

int strIndex(char str[], subStr[]);

例如,对于 str="abcdebc"和 subStr="bc",它将返回 1(因为 1 是 str 中包含 subStr 的第一个索引),对于 str="ab"和 subStr="ab"它将返回 0。如果str中不包含subStr(例如str="abc", subStr="aa"),则返回-1。

这就是我尝试做的:

int strIndex(char str[], char subStr[])
{
if (strcmp(str, subStr) == 0)
return 0;
else if (strcmp(str + (strlen(str1) - strlen(subStr)), subStr) == 0)
return strlen(str) - strlen(subStr);
else
//return without the last element of "str" array
}

但是是否可以在没有数组的 lest 元素的情况下调用递归?

最佳答案

该函数可以如下所示

#include <stdio.h>
#include <string.h>

int indexOf( const char *s1, const char *s2 )
{
size_t n1 = strlen( s1 );
size_t n2 = strlen( s2 );

if ( n1 < n2 )
{
return -1;
}
else if ( strncmp( s1, s2, n2 ) == 0 )
{
return 0;
}
else
{
int rtn = 1 + indexOf( s1 + 1, s2 );
return rtn == 0 ? -1 : rtn;
}
}

int main( void )
{
const char *s = "abcdebc";
const char *t = "bc";

printf( "Index of \"%s\" in \"%s\" is %d\n", t, s, indexOf( s, t ) );
}

程序输出为

Index of "bc" in "abcdebc" is 1

关于c - 返回字符串中包含子字符串的第一个索引的递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35023754/

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