You'd be looking for strcmp()
from the header <string.h>
.
Note that you need a string — 'Lee'
is not a string but a multi-character constant, which is allowed but seldom useful, not least because the representation is defined by the compiler, not the C standard.
If you are looking to compare two strings — call the pointers to them first
and second
, then you write:
if (strcmp(first, second) == 0) // first equal to second
if (strcmp(first, second) <= 0) // first less than or equal to second
if (strcmp(first, second) < 0) // first less than second
if (strcmp(first, second) >= 0) // first greater than or equal to second
if (strcmp(first, second) > 0) // first greater than second
if (strcmp(first, second) != 0) // first unequal to second
This, in my view, makes it clear what the comparison is and so the notation should be used. Note that strcmp()
may return any negative value to indicate 'less than' or any positive value to indicate 'greater than'.
You will find people who prefer:
if (strcmp(first, second)) // first unequal to second
if (!strcmp(first, second)) // first equal to second
IMO, they have the advantage of brevity but the disadvantage of being less clear than the explicit comparisons with zero. YMMV.
Be cautious about using strncmp()
instead of strcmp()
, which was suggested in one answer. If you have:
if (strncmp(first, "command", 7) == 0)
then if first
contains "commander"
, the match will be valid. If that's not what you want but you want to use strncmp()
anyway, you would write:
if (strncmp(first, "command", sizeof("command")) == 0)
This will correctly reject "commander"
.