C - Reverse string search

I just noticed that there is no strrstr() function in the standard C library.

I needed that for a project, using ANSI-C. So I wrote it.

Here's the code, maybe it can be helpfull for someone else... :

char * strrstr( char * s1, char * s2 );
char * strrstr( char * s1, char * s2 )
{
    char * ss1;
    char * sss1;
    char * sss2;
    
    if( *( s2 ) == '\0' )
    {
        return s1;
    }
    
    ss1 = s1 + strlen( s1 );
    
    while( ss1 != s1 )
    {
        --ss1;
        
        for( sss1 = ss1, sss2 = s2; ; )
        {
            if( *( sss1++ ) != *( sss2++ ) )
            {
                break;
            }
            else if ( * sss2 == '\0' )
            {
                return ss1;
            }
        }
    }
    
    return NULL;
}

Comments

Author
Micke Nordin
Date
12/21/2011 10:05
Hi,

this is useful to me. Would it be ok if I used this for a project released under GPL v.3 or any later version? I will of course give you credit in the Authors file.

Micke Nordin
Author
Jean-David Gadina
Date
01/03/2012 08:13
Thanks for the comment. You're free to use this code if it's useful to you.

Add a comment