网站推广.NET

网站推广.NET

strcmp在c语言中是什么意思?

来源:互联网

strcmp在c语言中的意思是:

strcmp函数是string compare(字符串比较)的缩写,用于比较两个字符串并根据比较结果返回整数。基本形式为strcmp(str1,str2),若str1=str2,则返回零;若str1str2,则返回正数。

当s1

当s1=s2时,返回值= 0;

立即学习“C语言免费学习笔记(深入)”;

当s1>s2时,返回正数。

即:两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇'\0'为止。如:

1."A"

 2."A"

3."Apple"

4."A"

 5."compare"

特别注意:strcmp(const char *s1,const char * s2)这里面只能比较字符串,即可用于比较两个字符串常量,或比较数组和字符串常量,不能比较数字等其他形式的参数。

ANSI标准规定,返回值为正数,负数,0 。而确切数值是依赖不同的C实现的。

  • 当两个字符串不相等时,C标准没有规定返回值会是1 或 -1,只规定了正数和负数。

  • 有些会把两个字符的ASCII码之差作为比较结果由函数值返回。但无论如何不能以此条依据作为程序中的流程逻辑。

代码:

#include <string.h>#include <memcopy.h>#undef strcmpint strcmp(p1,p2){    const char *p1;        const char *p2;        register const unsignedchar *s1=(const unsignedchar*)p1;        register const unsignedchar *s2=(const unsignedchar*)p2;        unsigned reg_charc1,c2;     do    {        c1=(unsigned char)*s1++;                c2=(unsigned char)*s2++;                if(c1==&#39;\0&#39;)                    returnc1-c2;         }     while(c1==c2);            return c1-c2;        }     libc_hidden_builtin_def(strcmp)//以上代码是K&R C规范的,ASCI C的在下面 /*strcmp function*/#include <string.h> int(strap)(const char *sl,const char *s2){    /*compare unsigned char sl[],s2[]*/    for(;*sl==*s2;++sl,++s2)        if(*sl==&#39;\0&#39;)            return(0);    return((*(unsignedchar*)sl<*(unsignedchar*)s2)?-1:+1);}

标签: strcmp是什么意思

抱歉,评论功能暂时关闭!