This documentation is copyright © 1998-2001 Sandro Sigala <sandro@sigala.it>.
All rights reserved.

Released under the GNU General Public License.

Return to index Return to header Previous symbol Next symbol

strncmp

Prototype

#include <string.h>

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

Description

Compares the first n characters of the two strings s1 and s2 (the comparison is interrupted before the terminating null characters). It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.

Implementation

View source
#include <string.h>

int strncmp(const char *s1, const char *s2, size_t n)
{
    const unsigned char *sp1 = (const unsigned char *)s1;
    const unsigned char *sp2 = (const unsigned char *)s2;

    for (; n > 0; ++sp1, ++sp2, --n)
	if (*sp1 != *sp2)
	    return (*sp1 < *sp2) ? -1 : 1;
	else if (*sp1 == '\0')
	    return 0;

    return 0;
}

Example

View source
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char *s1 = "abc", *s2 = "abcd";
    int retvalue;

    retvalue = strcmp(s1, s2);
    printf("'%s' %s '%s'\n", s1,
	   ((retvalue < 0) ? "<" :
	    (retvalue > 0) ? ">" : "=="), s2);
    /* Prints "'abc' < 'abcd'". */

    retvalue = strncmp(s1, s2, 3);
    printf("'%s' %s '%s'\n", s1,
	   ((retvalue < 0) ? "<" :
	    (retvalue > 0) ? ">" : "=="), s2);
    /* Prints "'abc' == 'abcd'". */

    return EXIT_SUCCESS;
}

References

ISO C 9899:1990 7.11.4.4