Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare strings in an "if" statement? [duplicate]

Tags:

c

string

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?

like image 743
lakam99 Avatar asked Nov 22 '11 05:11

lakam99


People also ask

Can you use == to compare strings?

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.

How do you compare strings in if loops?

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.

Can the IF function be used in comparing strings?

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.


2 Answers

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

like image 114
Kaslai Avatar answered Sep 20 '22 06:09

Kaslai


if(strcmp(aString, bString) == 0){
    //strings are the same
}

godspeed

like image 23
Trevor Arjeski Avatar answered Sep 20 '22 06:09

Trevor Arjeski