2

编辑:更改标题以反映帖子中的两种方法。

我正在尝试比较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 
4

7 回答 7

11

您的问题在于您如何使用strcmp. strcmp当字符串相等时返回 0(计算结果为 false)(当字符串“有序”时返回正数,当字符串“无序”时返回负数)。

于 2012-04-25T18:25:42.100 回答
6

当两个字符串相同时, strcmp返回 0,并且在 C 中 0 的计算结果为 false。尝试:

if(strcmp(test2, test)==0)
于 2012-04-25T18:26:00.040 回答
4

根据 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.

改变你的条件if(!strcmp(test2, test)),它应该工作。

于 2012-04-25T18:27:07.217 回答
2

如果字符串相等,strcmp() 返回 0。例如,参见http://www.cplusplus.com/reference/clibrary/cstring/strcmp/

于 2012-04-25T18:26:15.877 回答
2

strcmp()相等时返回 0

于 2012-04-25T18:27:08.647 回答
1

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 
$ 
于 2012-04-25T18:29:53.330 回答
1

man strcmp: "strcmp() 函数比较两个字符串 s1 和 s2。如果发现 s1 分别小于、匹配或大于,它将返回一个小于、等于或大于零的整数s2。”

于 2012-04-25T18:34:19.193 回答