当我明确声明一个字符串的值,然后将其与自身进行比较时,系统返回 FALSE。这与系统添加的额外'\0'字符有关吗?我应该如何改进我的代码以使其成为现实?
char name[5] = "hello";
if(name == "hello")
{
...
}
最佳答案
你不能(有用地)使用 !=
或 ==
比较字符串,你需要使用 strcmp
这样做的原因是因为 !=
和 ==
只会比较那些字符串的基地址。不是字符串的内容。
不要使用预定义的数组大小,例如 char name[5] = "hello";
您可以使用 char name[] = "hello";
或 char name[6] = "hello";
使用时
#include <stdio.h>
#include <string.h>
int main()
{
char a[] = "hello";
char b[] = "hello";
if (strcmp(a,b) == 0)
printf("strings are equal.\n");
else
printf("strings are not equal.\n");
return 0;
}
关于C弦长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43556820/