c语言字符和字符串比较(STRCMP和==) 您所在的位置:网站首页 指针怎么赋值字符串数字 c语言字符和字符串比较(STRCMP和==)

c语言字符和字符串比较(STRCMP和==)

2024-01-14 12:14| 来源: 网络整理| 查看: 265

字符串比较

1.字符比较用==号,既可以用常量也可以用变量比较

char a,b;    if(a==b)   {         printf("yes");   }

2.strcmp比较字符只能用常量,否则会报错

例如:

char a,b;    if(strcmp(a,b)!=0)   {         printf("yes");   }

报错:error: invalid conversion from 'char' to 'const char*' [-fpermissive]|

3.字符可以直接用=号赋值

字符串比较 int main() { char *str1="hello"; char str2[]="hello"; printf("%d\n",str1=="hello"); printf("%d\n",str2=="hello"); printf("%d\n",strcmp(str1,"hello")); printf("%d\n",strcmp(str2,"hello")); return 0; } 输出结果为1 0 0 0

1.字符串变量比较不能直接用==,但是可以用变量地址和字符串用==比较,如果地址相同,字符串会相等

char *str1 = “hello”;和”hello”的地址是相同的,所以返回结果相等

str2 == “hello”地址不相等。char str2[] = “hello”; 这里str2并不是指针,类型里已经说明它是一个数组,所以这会是另一个内存地址,于是str2与”hello”的地址是不同的。

综上:字符串的比较不能用==

2.字符串比较用strcmp函数

strcmp(str1,”hello”),strcmp(str2,”hello”)都是成立的 由于”hello”是字符串常量,编译器会进行优化: 所有的”hello”都是相同的,整个程序中只需要有一个”hello”字符串。

然后所有引用”hello”这个字符串的“指针变量”都赋值成相同的地址。  

3.字符串赋值不能用=



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有