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返回值的定义,可以说明两个字符串是相等的。
再考虑如下程序段,在第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;最终执行,输出的结果如下所示:
再看看大小写不一样的情况:
#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;
}