c语言字符串基础示例,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返回值的定义,可以说明两个字符串是相等的。

9d4db5adc49294c3af2c988bb6b4ef0a.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;最终执行,输出的结果如下所示:

d16e3be4e220adc67d57a5c296ad984d.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;

}

我们知道,ASCII码中大写的“A"排在小写的“a”的前面,所以就有A

bebacf5b5257f18410d827592794fc8c.png

我们在上述代码的第10行之前插入一行代码,如下程序段:

#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));

printf("%d\n", 'a' - 'A');

return 0;

}

运行一下的结果如下所示,这说明小写字母“a”的ASCII码的位置相对于大写字母“A”的ASCII码的位置大32。

9281270d03a496e1ba1caec72fae3d9c.png

如果让我们自己来写函数strcmp,我们可以这样写↓

#define _CRT_SECURE_NO_WARNINGS

#include

#include

int mycmp(const char* s1, const char* s2)

{

int idx = 0;

while (s1[idx] == s2[idx] && s1[idx] != '\0')

idx++;

return s1[idx] - s2[idx];

}

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

{

char s1[] = "abcdefg";

char s2[] = "abcde";

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

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

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值