![](/img/trans.png)
[英]C language - strcmp returns 0 always and strcpy not copying the string in another array
[英]Can strcpy affect strcmp results in c language?
编辑:更改标题以反映帖子中的两种方法。
我正在尝试比较c语言中的两个字符串,但由于某种原因,它始终打印两个字符串不相等
#include <stdio.h>
#include <string.h>
int main()
{
/* A nice long string */
char test[30]="hellow world";
char test2[30];
// to copy string from first array to second array
strcpy(test2, test);
/* now comparing two stering*/
if(strcmp(test2, test))
printf("strigs are equal ");
else
printf("not equal \n");
printf("value of first string is %s and second string is %s",test,test2);
printf("length of string1 is %zu and other string is %zu ",strlen(test2),strlen(test2));
}
我总是得到输出
not equal
value of first string is hellow world and second string is hellow worldlength of string1 is 12 and other string is 12
你的问题在于你如何使用strcmp
。 当字符串相等时, strcmp
返回0(其值为false)(当字符串为“按顺序”时返回正数,当它们“乱序”时返回负数)。
当两个字符串相同时, strcmp返回0,而在C中,0的计算结果为false。尝试:
if(strcmp(test2, test)==0)
根据C ++引用Return value of strcmp -A zero value indicates that both strings are equal. -A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.
Return value of strcmp -A zero value indicates that both strings are equal. -A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.
将你的条件改为if(!strcmp(test2, test))
,它应该有效。
如果字符串相等,strcmp()返回0。 例如, 参见http://www.cplusplus.com/reference/clibrary/cstring/strcmp/
strcmp()
在相等时返回0
如果给定的两个字符串相等,则strcmp
返回0。
我还修复了一些拼写错误,在最后一个printf()
你已经两次调用了strlen(test2)
! - 纠正这一点
#include <stdio.h>
#include <string.h>
int main()
{
/* A nice long string */
char test[30]="hello world";
char test2[30];
// to copy string from first array to second array
strcpy(test2, test);
/* now comparing two stering*/
if(!strcmp(test2, test))
printf("strigs are equal \n");
else
printf("not equal \n");
printf("value of first string is %s \nsecond string is %s \n", test, test2);
printf("length of string1 is %zu \nsecond string is %zu \n",strlen(test), strlen(test2));
return 0;
}
输出:
$ ./a.out
strigs are equal
value of first string is hello world
second string is hello world
length of string1 is 11
second string is 11
$
man strcmp:“strcmp()函数比较两个字符串s1和s2。如果找到s1,则返回小于,等于或大于零的整数,小于,匹配或大于S2“。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.