I want to test and see if a variable of type "char" can compare with a regular string like "cheese" for a comparison like:
#include <stdio.h>
int main()
{
char favoriteDairyProduct[30];
scanf("%s",favoriteDairyProduct);
if(favoriteDairyProduct == "cheese")
{
printf("You like cheese too!");
}
else
{
printf("I like cheese more.");
}
return 0;
}
(What I actually want to do is much longer than this but this is the main part I'm stuck on.) So how would one compare two strings in C?
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
Use the equals() method to check if 2 strings are the same. The equals() method is case-sensitive, meaning that the string "HELLO" is considered to be different from the string "hello". The == operator does not work reliably with strings. Use == to compare primitive values such as int and char.
No. "if" command can only be used to compare numerical values and single character values. For comparing string values, there is another function called strcmp that deals specifically with strings.
You're looking for the function strcmp
, or strncmp
from string.h
.
Since strings are just arrays, you need to compare each character, so this function will do that for you:
if (strcmp(favoriteDairyProduct, "cheese") == 0)
{
printf("You like cheese too!");
}
else
{
printf("I like cheese more.");
}
Further reading: strcmp at cplusplus.com
if(strcmp(aString, bString) == 0){
//strings are the same
}
godspeed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With