Recursively search a string to find a character

I will admit, this is a homework problem, but I have tried writing the code and am having a bit of trouble getting it working.

The function is supposed to search through a string to find the first instance of a character and return it's index. I have it so that it returns the value of -1 if the character is not found, which is a requirement, but I can't get it to return the index correctly.

This is what I have currently that does not work accurately:
1
2
3
4
5
6
7
8
9
10
11
12
13
int str_char_find_r ( const char str1[], const char search_char )
{

  if (*str1 == '\0')
    return -1;
  else if (*str1 == search_char)
    return 1;
  else
    return (str_char_find_r(str1 + 1, search_char));

  return -1;

}


Any help would be great!
Thanks
Assuming you need to use recursion you could have str_char_find_r also take an int for the current index. When you call the function you would pass in 0 for the index and each recursion you would increment it.
closed account (zwA4jE8b)
return (str_char_find_r(++str1, search_char));

because str1 is a pointer you can increment it using ++, just make sure you use it pre and not post.
I agree with LBEaston. If you don't want to change the signature of your func, you could code it with the help of an auxillary function. Or you could use the extra as a "start from" index, and default it to 0.

You also have one too many returns, which some compilers will dislike (inaccessible code warning).
Last edited on
Thank you guys for your replies, but the function was given to us and cannot be changed.
Topic archived. No new replies allowed.