信息来自RHEL,man page:
STRCMP(3) Linux Programmer's Manual
NAME
strcmp, strncmp - compare two strings
SYNOPSIS
#include <string.h>
int strcmp(const char *s1, const char *s2);
int strncmp(const char *s1, const char *s2, size_t n);
DESCRIPTION
The strcmp() function compares the two strings s1 and s2. 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.
The strncmp() function is similar, except it compares the only first (at most) n bytes of s1 and s2.
RETURN VALUE
The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the
first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.
CONFORMING TO
SVr4, 4.3BSD, C89, C99.
函数实现:
strcmp()函数实现:
0.功能描述:
字符串比较函数,
逐字符
比较字符串s1(source)
和字符串s2(dest)
:
源字符串大于
目标字符串时—-> 返回字符串s1从前往后第一个大于字符串s2的对应字符ASCII差值(为正)
源字符串小于
目标字符串时—-> 返回字符串s1从前往后第一个小于字符串s2的对应字符ASCII差值(为负)
源字符串等于
目标字符串时—-> 返回0
1.原型:
#include <string.h>
int strcmp(const char *s1, const char *s2);
2.参数:
s1即源字符串。
s2目标字符串。
3.实现:
A.实现一:
//定义FALSE宏值
#define FALSE ('z' - 'A')
int my_strcmp(const char *s1, const char *s2)
{
int result = 0;
//参数判断
if(NULL == s1 || NULL == s2){
return FALSE;
}
//逐个字符查找比对,并记录差值
while(!(result = *(unsigned char *)s1 - *(unsigned char *)s2) && *s2){
s1++;
s2++;
}
//返回
return result;
}
B.实现二:
#define FALSE ('z' - 'A')
int my_strcmp2(const char *s1, const char *s2)
{
if(NULL == s1 || NULL == s2){
return FALSE;
}
while(*s1 == *s2 && *s2){
s1++;
s2++;
}
return *(unsigned char *)s1 - *(unsigned char *)s2;
}
strncmp()函数实现:
0.功能描述:
参照strcmp函数,区别之处在于,逐个字符比对,判断前n个字符。并且当n为零时,返回为零
1.原型:
#include <string.h>
int my_strncmp(const char *s1, const char *s2, size_t n)
2.参数:
s1,s2:对应strcmp函数
n:用来标示此函数应对比前n个字符
3.实现:
A.实现一:
#define FALSE ('z' - 'A')
int my_strncmp(const char *s1, const char *s2, size_t n)
{
int result = 0;
if(NULL == s1 || NULL == s2 || 0 > n){
return FALSE;
}
if(0 == n){
return 0;
}
while(n-- && !(result = *(unsigned char *)s1 - *(unsigned char *)s2) && *s2){
s1++;
s2++;
}
return result;
}
B.实现二:
#define FALSE ('z' - 'A')
int my_strncmp(const char *s1, const char *s2, size_t n)
{
if(NULL == s1 || NULL == s2 || 0 > n){
return FALSE;
}
if(0 == n){
return 0;
}
while(n-- && (*s1 == *s2) && *s2){
s1++;
s2++;
}
return *(unsigned char *)s1 - *(unsigned char *)s2;
}
=============文章结束==============
小菜总结,如有不当,欢迎批评!