c语⾔字符和字符串⽐较(STRCMP和==)
字符串⽐较
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.字符串赋值不能⽤=

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。