C语言之strcmp函数,C语言基础之字符串函数strcmp

strcmp

int strcmp(const char* s1, const char* s2);

◆比较两个字符串,返回:

▲ 0:s1 == s2

▲ 1:s1 > s2

▲ -1:s1 < s2

【例1】

#define _CRT_SECURE_NO_WARNINGS

#include #include int main(int argc, char const* argv[])

{

char s1[] = "abc";

char s2[] = "abc";

printf("%d\n", strcmp(s1, s2));

return 0;

}

执行后结果如下图所示,根据strcmp返回值的定义,可以说明两个字符串是相等的。

3f4912939ded9ebf09495bcacd9d9f40.png

再考虑如下程序段,在第9行加入了新的printf代码,我们探讨尝试直接使用“==”运算符进行判断数组大小是否可行:

#define _CRT_SECURE_NO_WARNINGS

#include #include int main(int argc, char const* argv[])

{

char s1[] = "abc";

char s2[] = "abc";

printf("%d\n", s1 == s2);

printf("%d\n", strcmp(s1, s2));

return 0;

}

我们可以看到如下图所示的结果,由于“==”运算符在左值和右值不相等时返回值0,说明s1[]和s2[]是不等的,本质上也就是char* s1≠char* s2,即两个指针所指向的地址是不同的。

【例2】

#define _CRT_SECURE_NO_WARNINGS

#include #include int main(int argc, char const* argv[])

{

char s1[] = "abc";

char s2[] = "bbc";

printf("%d\n", strcmp(s1, s2));

return 0;

}

这段程序设计为字符串s1[]和字符串s2[]在第一个字符就不相同,根据常识在字母表中b处于a的后面,期望返回的结果是-1;最终执行,输出的结果如下所示:

803e363dc05ee1636d87d2606129c01a.png

再看看大小写不一样的情况:

#define _CRT_SECURE_NO_WARNINGS

#include #include int main(int argc, char const* argv[])

{

char s1[] = "abc";

char s2[] = "Abc";

printf("%d\n", strcmp(s1, s2));

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值