吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C/C++ 中的 strcmp()

C/C++ 中的 strcmp()

来源:网络 | 更新时间:2022-01-13 13:44:46
strcmp() 是一个内置库函数,在<string.h>头文件中声明。此函数将两个字符串作为参数,并按字典顺序比较这两个字符串。 语法::
int strcmp(const char *leftStr, const char *rightStr);
在上面的原型中,函数 srtcmp 以两个字符串为参数,根据字符串的比较返回一个整数值。
  • strcmp() 按字典顺序比较两个字符串意味着它从第一个字符开始逐个字符开始比较,直到两个字符串中的字符相等或遇到 NULL 字符。
  • 如果两个字符串中的第一个字符相等,则此函数将检查第二个字符,如果这也相等,则它将检查第三个字符,依此类推
  • 此过程将一直持续到任一字符串中的字符为 NULL 或字符不相等为止。

strcmp() 返回什么?

此函数可以根据比较返回三个不同的整数值:
  •  0 :当发现两个字符串相同时,值等于零。即两个字符串中的所有字符都相同。
// C program to illustrate
// strcmp() function
#include<stdio.h>
#include<string.h>

int main()
{ 

char leftStr[] = "g f g";
char rightStr[] = "g f g";

// Using strcmp()
int res = strcmp(leftStr, rightStr);

if (res==0)
printf("Strings are equal");
else 
printf("Strings are unequal");

printf("nValue returned by strcmp() is: %d" , res);
return 0;
}
输出:
Strings are equal
Value returned by strcmp() is:  0
  • 大于零 ( >0 ):当 leftStr 中的第一个不匹配字符的 ASCII 值大于 rightStr 中的相应字符时,返回大于零的值
// C program to illustrate
// strcmp() function
#include<stdio.h>
#include<string.h>
int main()
{ 
// z has greater ASCII value than g
char leftStr[] = "zfz";
char rightStr[] = "gfg";

int res = strcmp(leftStr, rightStr);

if (res==0)
printf("Strings are equal");
else 
printf("Strings are unequal");

printf("nValue of result: %d" , res);

return 0;
}
输出:
Strings are unequal
Value returned by strcmp() is:  19
  • 小于零 ( <0 ):当 leftStr 中的第一个不匹配字符的 ASCII 值小于 rightStr 中的相应字符时,返回小于零的值。
// C program to illustrate
// strcmp() function
#include<stdio.h>
#include<string.h>
int main()
{ 
// b has less ASCII value than g
char leftStr[] = "bfb";
char rightStr[] = "gfg";

int res = strcmp(leftStr, rightStr);

if (res==0)
printf("Strings are equal");
else 
printf("Strings are unequal");

printf("nValue returned by strcmp() is: %d" , res);


return 0;
}
输出:
Strings are unequal
Value returned by strcmp() is:  -5
要点:当字符串不相同时,你会发现 strcmp() 函数返回的值是这两种情况下 leftStr 和 rightStr 中第一个不匹配字符的 ASCII 值之差。

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com