[英]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.