0

Write the function my_strrchr(). The function has two parameters: a const char * s pointing to the first character in a C-style string, and a char, c. Return a pointer to the last appearance of c appearing inside s and NULL (0) if c does not appear inside s.
is this the right way to go backward, grap the first time the char appear and return it?

const char * my_strrchr(const char * s, char c)
{
    int b = 0;
    char first = *s;
    for(int i = strlen(s)-1; i > 0 ; i--)
    {
        if(s[i] == c) 
        {
            return s;
            break;
        }   
    }
    return '\0';
}
int main()
{
    char cstr[50] = "Abadabadoo!";
    cout << "\nmy_strrchr(cstr, 'a') expects adoo!" << endl;
    cout << "  -- " << my_strrchr(cstr, 'a') << endl;
}
2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by qvyhnl
0

line 10. The break is unnecessary because of the return statement on the previous line.

line 9: wrong. You want return &s[i]; line 19: That will most likely display 0 if the function every returns NULL, which may not be what you intend.


Otherwise your program looks good :)

Edited by Ancient Dragon: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.