C语言判断两字符串是否相等——strcmp函数

好久没有写c语言了。
前两天写了个代码,if语句里判断两字符串是否相等,如果相等则执行if语句的代码块。用惯了python的我,直接就用==来比较了。结果传入相等的字符串,运行时还是进不去条件判断。打印log看了一下,判断语句值为0,也就是相等的字符串用==判断,被认为是不同的。
后续搜了一些资料,理一下这个问题。今天,就把这些记录下来。

一、字符串比较不能直接用==

分几种情况:
1、字符串变量比较。
两个变量即便相等,==的结果也是0。

char str3[]="hello,world";
char str4[]="hello,world";
printf("%d\n", str3==str4);

打印出的结果为0。

2、字符串指针比较
字符串指针可以用==比较。如果两个指针指向的是相同的地址,则结果为1。

char *str = "hello,world";
char *str2 = "hello,world";
printf("%d\n", str==str2);

打印结果为1。
这里,指针str和str2都指向了“hello,world”的地址。

3、字符串指针和字符串用==比较,如果地址相同,结果为1。

char *str="hello,world";
printf("%d\n", str=="hello,world");

打印结果还是1。

二.字符串比较用strcmp函数

==判断,要考虑的因素太过繁琐。我们可以直接用strcmp函数来比较两个字符串。

int ret = strcmp(str1, str2);

使用strcmp函数需要包含头文件#include <string.h>
返回值有三种情况:如果串1和串2相等,则返回值为0。
串1 > 串2,返回一个正整数;
串1 < 串2,返回一个负整数。

char *str="hello,world";
char *str2="hello,world";
char str3[]="hello,world";
char str4[]="hello,world";

printf("%d\n", !strcmp(str3, str4));
printf("%d\n", !strcmp(str, str2));
printf("%d\n", !strcmp(str, "hello,world"));

返回的结果都为1。

猜你喜欢

转载自blog.csdn.net/qq_32608527/article/details/132689932