Edit: Changed title to reflect both methods in post.
I’m trying to compare two strings in c language as below but for some reason it’s always printing that both strings are not equal
#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));
}
I’m always getting output as
not equal
value of first string is hellow world and second string is hellow worldlength of string1 is 12 and other string is 12
Your problem is with how you’re using
strcmp.strcmpreturns 0 (which evaluates as false) when the strings are equal (and returns a positive number when the strings are “in order” and a negative number when they’re “out of order”).