Jump to: navigation, search

Description

The strncmp() function compares up to n characters of the string pointed to by s1 to the string pointed to by s2.

Return value

The strncmp() function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2 in the first n bytes.

Prototype

Declared in string.h

The C89/C99 prototype is:

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

Implementation

In standard C, this can be implemented as:

#include <stddef.h>
int strncmp(const char* s1, const char* s2, size_t n)
{
    while(n--)
        if(*s1++!=*s2++)
            return *(unsigned char*)(s1 - 1) - *(unsigned char*)(s2 - 1);
    return 0;
}

Compilable unit, portable C90 in implementation namespace; public domain; past reviewers: none; current reviews: none

References

The C Standard, 7.21.4.4 (C99 numbering)

Personal tools
Personal tools
Tidy_icons
not logged in