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

Recommended Answers

All 2 Replies

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 :)

Thanks a lot =)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.