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. strcmp returns 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").
strcmp returns 0 when two strings are the same, and 0 evaluates to false in C. Try:
if(strcmp(test2, test)==0)
As per C++ reference
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.
Alter your condition to if(!strcmp(test2, test)) and it should work.
strcmp() returns 0 if the strings are equal. See, for example, http://www.cplusplus.com/reference/clibrary/cstring/strcmp/
strcmp() returns 0 on equality
man strcmp: "The strcmp() function compares the two strings s1 and s2. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2."
strcmp return 0 if the given two strings are equal.
I have also fixed few spelling mistakes and in the last printf() you have called strlen(test2) two times! - correct that as well
#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;
}
Output:
$ ./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
$
Related
I created two arrays 'TEST' and 'arr' below,both contain characters "ABCDE".
#include <stdio.h>
#define TEST "ABCDE"
int main()
{
char arr[5];
int i;
for(i=0;i<5;i++)
{
arr[i] = i + 65;
}
printf("%s\n",arr);
printf("%zd %zd",sizeof arr,sizeof TEST);
return 0;
}
And the output is
ABCDE
5 6
Why are their size different, given that these two arrays both carry 5 characters ?
(I konw there is a null character at the end of each character string.)
After the macro expansion, the line
printf("%zd %zd",sizeof arr,sizeof TEST);
will be:
printf("%zd %zd",sizeof arr,sizeof "ABCDE" );
String literals will always have a terminating null character added to them. Therefore, the type of the string literal is char[6]. The expression sizeof "ABCDE" will therefore evaluate to 6.
However, the type of arr is char[5]. Space for a null-terminating character will not be automatically added. Therefore, the expression sizeof arr will evaluate to 5.
Also, it is worth noting that the following line is causing undefined behavior:
printf("%s\n",arr);
The %s printf format specifier requires a null-terminated string. However, arr is not null-terminated.
If you want to print the array, you must therefore limit the number of characters printed to 5, like this:
printf( "%.5s\n", arr );
Or, if you don't want to hard-code the length into the format string, you can also do this:
printf( "%.*s\n", (int)sizeof arr, arr );
using the following program in C, the string comparison is not working:
#include<stdio.h>
#include<string.h>
int main(){
char ch[]="ABC";
printf("%d \n", strlen(ch)); // output 3
printf("%d \n", strlen("ABC")); // output 3
if(strcmp("ABC",ch)){
printf("\n Matched");
}else{
printf("\n Not matched"); // this will be output
}
if("ABC" == ch){
printf("\n Matched");
}else{
printf("\n Not matched"); // this will be output
}
}//ends main
the output is:
3
3
Not matched
Not matched
Why the string is not matching?
With "ABC" == ch you compare two pointers, you don't compare what the pointers are pointing to. And these two pointers will never be equal.
And the strcmp function returns zero if the strings are equal. Zero is considered "false" in C, and all non-zero values are "true".
String literals in C are really arrays of (read-only) characters, including the terminator. As all arrays they decay to pointers to their first elements when they are used in most expressions.
It would work if you change the double qoutes to single qoutes: "ABC" to 'ABC'
I would like to ask how to identify a sequence in C for example AAAAA & ddddd the sequence is all of the inputted characters must be the same.. How is it possible to achieve that? Do I need to use char ? Here is what i had try
#include<stdio.h>
int main() {
char ch;
scanf("%cccc", &ch);
if (ch = 'c')
printf(&ch);
else
printf("Character is Not the same sequence");
return (0);
}
To compare two characters:
char a = 'a';
char b = 'b';
return a == b; // this compares integer values of two characters
// and returns 1/0 if they do match/do not match
To compare strings:
char str1 = "AAAAA";
char str2 = "aaaaa";
return strcmp(str1, str2);
man strcmp(3):
The strcmp() function compares the two strings s1 and s2. It returns
an integer less than, equal
to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater
than s2.
The strncmp() function is similar, except it compares the only first (at most) n bytes of s1 and
s2.
Your code contains few bugs. %c format is for scanning single character, use %s for strings. Here:
if (ch = 'c')
you assigned 'c' to ch, not what you wanted. Use == in C for comparisons.
I would try this:
Accept a string as input (instead of a character)
Set up a loop to walk through the string, character by character
Your first character will be the "good" value
If at any time, you encounter a different character, fail out of the loop
If you reach the end of the string without failing, you succeed
Create a Macro for the pattern you want to find. typecast your input to the size of the pattern you want to recognise. Subtract both. If 0 pattern matched. Else,shift right 1 bit and repeat. Example, Pattern to find #define wPAT 0x1234. Input=> U32 dwInput=0x12345678. Result= (U16)dwInput - wPAT . If 0,pattern found. Else, dwInput>>1 and repeat Result= (U16)dwInput - wPAT. Repeat 16 times to find if pattern is present or not
While writing a program i am filling the entries of a char array with digits. After doing so the length calculated for an array having no zero is correct but for an array starting with zero is zero!
Why is this result coming so!I am not able to interpret my mistake!?
int main()
{
int number_of_terms,no,j,i;
char arr[100];
char c;
scanf("%d",&number_of_terms);
for(i=0;i<number_of_terms;i++)
{
j=0;
while(c!='\n')
{
scanf("%d",&arr[j]);
if(c=getchar()=='\n')
break;
j++;
}
printf("Length is:%d\n",strlen(arr));
}
return 0;
}
for eg if i input my array elements as 4 5
lenght is 2
and if my array elements as 0 5
length is 0..
You are using "%d" in your format specifier, which produces an integer, and you are passing in the address of a character array. This is, exactly like your title says, undefined behaviour. In particular, the value zero will take up 4 of the cells in your string, and will write zero to all of those. Since the character with value zero is the end marker, you get zero length string. However, on another architecture, the second character would probably cause a crash...
If you want to store integers in an array, you should use int arr[...];. If you want to store characters, use "%c".
You are copying the value 0 into the array. This eqals the character '\0' which is used to terminate strings. What you want is to copy the character '0' (has the value 48, see an ascii table).
Change %d to %c to interpret the input has character instead of decimal.
scanf("%c",&arr[j]);
Also your "string" in arr is not zero terminated. After all the characters of your string, you have to end the string with the value 0 (here a decimal is correct). strlen needs it, because it determines the length of the string by traversing the array and counting up until it finds a 0.
This question already has answers here:
How does strcmp() work?
(9 answers)
Closed 5 years ago.
I am learning about strcmp() in C. I understand that when two strings are equal, strcmp returns 0.
However, when the man pages state that strcmp returns less than 0 when the first string is less than the second string, is it referring to length, ASCII values, or something else?
In this sense, "less than" for strings means lexicographic (alphabetical) order.
So cat is less than dog because cat is alphabetically before dog.
Lexicographic order is, in some sense, an extension of alphabetical order to all ASCII (and UNICODE) characters.
A value greater than zero indicates that the first character that does not match has a greater value in the first string than in the second, and a value less than zero indicates the opposite.
C99 7.21.4:
The sign of a nonzero value returned by the comparison functions
memcmp, strcmp, and strncmp is determined by the sign of
the difference between the values of the first pair of characters (both
interpreted as unsigned char) that differ in the objects being
compared.
Note in particular that the result doesn't depend on the current locale; LC_COLLATE (see C99 7.11) affects strcoll() and strxfrm(), but not strcmp().
int strcmp (const char * s1, const char * s2)
{
for(; *s1 == *s2; ++s1, ++s2)
if(*s1 == 0)
return 0;
return *(unsigned char *)s1 < *(unsigned char *)s2 ? -1 : 1;
}
Look out the following program, here I am returning the value depending upon the string you have typed. The function strcmp retrun value according to ASCII value of whole string considered totally.
For eg. str1 = "aab" and str2 = "aaa" will return 1 as aab > aaa.
int main()
{
char str1[15], str2[15];
int n;
printf("Enter the str1 string: ");
gets(str1);
printf("Enter the str2 string : ");
gets(str2);
n = strcmp(str1, str2);
printf("Value returned = %d\n", n);
return 0;
}