-3

I need to make a recursive function, that gets two char arrays, and return the first index where "subStr" appear in the "str".

Signature of the function:

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

For example- for str="abcdebc" and subStr="bc", it will return 1(because 1 is the first index where subStr contained in str), and for str="ab" and subStr="ab" it will return 0. If subStr doesn't contained in str(for example str="abc", subStr="aa"), it will return -1.

This is what I tried to do:

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
}

but does it possible to call in recurstion without the lest element of array?

jaldk
  • 123
  • 1
  • 7
  • 4
    And? We are not just going to do this for you. – NathanOliver Jan 26 '16 at 20:54
  • Post your implementation of the recursive function and explain how it is not working as you expect. – drescherjm Jan 26 '16 at 20:57
  • `str2-1` ?? invalid pointer!. – BLUEPIXY Jan 26 '16 at 21:05
  • Does it possible to take the last element from the array? – jaldk Jan 26 '16 at 21:07
  • This is very easy using `strstr()` and doing some basic pointer arithmetik. Try it yourself! I do not see where a recursion is sensible here. Are you sure that you understood the assignment right? – Ctx Jan 26 '16 at 21:09
  • This is from a test i'm solving, and I must use recursion – jaldk Jan 26 '16 at 21:13
  • @jaldk try solving it with the very basics. Don't use string functions. Compare character by character and think bout how to check for a substring in a string yourself. If you have problems solving it, why don't you ask the one who gave you that test? – Flikk Jan 26 '16 at 21:17

1 Answers1

1

The function can look the following way

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

The program output is

Index of "bc" in "abcdebc" is 1
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335