Home>Article>Backend Development> What does strcmp mean in c language?

What does strcmp mean in c language?

coldplay.xixi
coldplay.xixi Original
2020-07-06 14:39:06 38985browse

strcmp在c语言中的意思是string compare的缩写,用于比较两个字符串并根据比较结果返回整数,基本形式为strcmp(str1,str2),若【str1=str2】,则返回零,若【str1c10b2c95be749c9875455fa9ac3d062cstr2,则返回正数。

当s158c35089034f175399ab8f0dc565477fs2时,返回正数。

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

1."A"<"B"

2."A"<"AB"

3."Apple"<"Banana"

4."A"<"a"

5."compare"<"computer"

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

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

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

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

代码:

#include  #include  #undef strcmp int 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=='\0') returnc1-c2; } while(c1==c2); return c1-c2; } libc_hidden_builtin_def(strcmp) //以上代码是K&R C规范的,ASCI C的在下面 /*strcmp function*/ #include  int(strap)(const char *sl,const char *s2) { /*compare unsigned char sl[],s2[]*/ for(;*sl==*s2;++sl,++s2) if(*sl=='\0') return(0); return((*(unsignedchar*)sl<*(unsignedchar*)s2)?-1:+1); }

相关学习推荐:C视频教程

The above is the detailed content of What does strcmp mean in c language?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn