Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a value matches a string

Tags:

c

I have a struct here with something like:

char *sname;
........
players[i].sname

equalling "James".

I need to check for equality between values like so:

if (players[i].sname == 'Lee')

but am not having much luck. Is there a str* function I should be using or is there anyway to fix up my if statement?

like image 349
Dominic Bou-Samra Avatar asked Oct 21 '09 02:10

Dominic Bou-Samra


1 Answers

The short answer: strcmp().

The long answer: So you've got this:

if(players[i].sname == 'Lee')

This is wrong in several respects. First, single-quotes mean "character literal" not "string literal" in C.

Secondly, and more importantly, "string1" == "string2" doesn't compare strings, it compares char *s, or pointers to characters. It will tell you if two strings are stored in the same memory location. That would mean they're equal, but a false result wouldn't mean they're inequal.

strcmp() will basically go through and compare each character in the strings, stopping at the first character that isn't equal, and returning the difference between the two characters (which is why you have to say strcmp() == 0 or !strcmp() for equality).

Note also the functions strncmp() and memcmp(), which are similar to strcmp() but are safer.

like image 74
Chris Lutz Avatar answered Oct 06 '22 17:10

Chris Lutz