【问题标题】:recursive function that return the first index where sub string contained in string [closed]返回字符串中包含的子字符串的第一个索引的递归函数[关闭]
【发布时间】:2016-01-26 20:54:08
【问题描述】:

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

函数签名:

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

例如,对于 str="abcdebc" 和 subStr="bc",它将返回 1(因为 1 是 subStr 包含在 str 中的第一个索引),对于 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
}

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

【问题讨论】:

  • 然后呢?我们不只是为你做这件事。
  • 发布您对递归函数的实现,并解释它如何无法按预期工作。
  • str2-1 ??指针无效!。
  • 是否可以从数组中取出最后一个元素?
  • 这很容易使用strstr() 并做一些基本的指针算法。自己试试吧!我看不出在这里递归是明智的。你确定你理解正确吗?

标签: c string recursion strcmp strlen


【解决方案1】:

函数可以如下所示

#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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 2013-10-02
    • 2016-05-04
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多