C标准库--strcmp、strncmp函数
1、The strcmp function
1.1、Synopsis
#include <string.h>
int strcmp(const char *s1, const char *s2);
1.2、Description
The strcmp function compares the string pointed to by s1 to the string pointed to by s2.
1.3、Returns
The strcmp function returns integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or les than the string pointed to by s2.
1.4、Implementing
/* strcmp function */
#include <string.h>
int (strcmp)(const char *s1, const char *s2)
{ /* compare unsigned char s1[], s2[] */
for (; *s1 == *s2; ++s1, ++s2)
if (*s1 == '\0')
return 0;
return ((* unsigned char *)s1 < * (unsigned char *)s2) ? -1 : +1);
}
1.5、Using
This function offers the quickest way to determine whether two null-terminateed strings match character for character. You can also use it to establish a lexical ordering between two strings, but that ordering can change among inolementations. If a portable result is important, you must write your own comparsion function, See strcoll and strxfrm.
2、The strcmp function
2.1、Synopsis
#include <string.h>
int strncmp(const char *s1, const char *s2, size_t n);
2.2、Description
The strncmp function compares not more than n characters (characters that follow a null characters are not compared) from the array pointed to by s1 to the array pointed to by s2.
2.3、Returns
2.4、Implementing
/* strncmp function */
#include <string.h>
int (strncmp)(const char *s1, const char *s2, size_t n)
{ /* compare unsigned char s1[max n], s2[max n] */
for (; 0 < n; ++s1, ++s2, --n)
if (*s1 != *s2)
return ((* (unsigned char *)s1 < *(unsigned char *) s2) ? -1 : =1);
else if (*s1 == '\0')
return (0);
return (0);
}
2.5、Using
The function offers the quickest way to determine whether two character sequences of the same known length match character for character up to and including any null character in both. You can also use it to establish a lexical ordering between two such character swquences, but that ordering can change among implementations. If a portable resulet is important, you must write your own comparison fcunction.