C Programming/C Reference/string.h/strncmp

strncmp() is a standard-library function that compares two strings up to a specified length. The function is declared in string.h, and is compatible with the following prototype:

int strncmp (const char * s1, const char * s2, size_t num);

The function compares the strings using a lexicographical ordering, but never examines more than num characters. It returns zero if the strings are equal, or if their first num characters are equal; otherwise, it returns a negative integer if s1 is less than s2, and a positive integer if s1 is greater than s2. A simple implementation might be as follows:

int strncmp (const char * const s1, const char * const s2, const size_t num)
{
    const unsigned char * const us1 = (const unsigned char *) s1;
    const unsigned char * const us2 = (const unsigned char *) s2;
 
    for(size_t i = (size_t)0; i < num; ++i)
    {
        if(us1[i] < us2[i])
           return -1;
        else if(us1[i] > us2[i])
           return 1;
        else if(! us1[i]) /* null byte -- end of string */
           return 0;
    }
 
    return 0;
}

In practice, however, real implementations are significantly optimized.

See alsoEdit

External linksEdit

Last modified on 18 October 2011, at 19:35