How to check if a char and a word are equal in c char word i

How to check if a char[] and a \"word\" are equal in c?

char[] word;

if(word==\"begin\")

{return BEGINnumber;}

Solution

You can use the library function strcmp() for this purpose.

See, in C language, a character array is a string. Also you want to compare it with the string literal, ultimately a string.

So, strcmp() function is used for this purpose. To use it, you need to include the header file <string.h> which stores the declaration of this function.

Now, strcmp() returns an integer. Its syntax is like strcmp(str1, str2) . It returns 0 if both the strings are zero.If they are not same, it returns the difference of two unequal characters found first. In simple words, str1 = \"ABC\" and str2 = \"ABD\". Then C - D = -1 is returned, If str2 was \"ABB\" then C - B = 1 would be returned.

In this way, non-zero value is returned if strings are not same. If it returns 0, it definitely means that both the strings are same.

So, here is the sample code for such comparison.:

#include <stdio.h>
#include<string.h>
void main() {
  
   char array1[ ] = \"Abc\";
  
   if( !strcmp ( array1,\"Abc\" ) )
   printf(\"true\");
   return 0;
}

The above code checks if array1[ ] and \"Abc\" values are same or not. If they are same, the result will be 0 right. So, I have used ! ahead strcmp() to reverse the number. i.e. !0 is considered as 1. In C, if(1) means if(true) so it goes inside the if condition and prints the result as both the strings are same.

In this code snippet provided in the question, you can compare it with:

if ( ! strcmp ( word, \"begin\" )

return BEGINnumber;

Do comment if there is any confusion in explanation. Thank you. :)

How to check if a char[] and a \

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site