In C, you can compare single characters (chars) by using the comparion operator ==, however, this method is not valid for comparing arrays of chars, or strings. Instead, you must use a function that compares each of the chars within the arrays in turn. This may sound complex to the beginner, but fortunately there is a standard C function that does this for you.
#include <string.h>
int strcmp(const char *s1, const char *s2);
int strncmp(const char *s1, const char *s2, size_t n);
The first, strcmp(), does exactly as described above, the second, strncmp(), checks only the first n characters of the array for equality.
Here is an example of how not to do things.
#include <stdio.h>
#include <string.h>
int main(void)
{
char *foo = "hello";
char *bar = "hello";
if (foo == bar) /* Wrong ! */
puts("Strings equal");
else
puts("Strings do not equal");
return 0;
}
Here are some examples of these functions in use.
#include <stdio.h>
#include <string.h>
int main(void)
{
char *foo = "hello";
char *bar = "world";
if (strcmp(foo, bar) == 0)
puts("Strings equal");
else
puts("Strings do not equal");
return 0;
}
/*
* Output
Strings do not equal
*
*/
This next example shows the consideration needed when reading a string from the user. It deals with removing the newline character from the input array. This issue is also covered here.
#include <stdio.h>
#include <string.h>
int main(void)
{
char Owner[] = "Hammer";
char buf[BUFSIZ];
printf ("You are at the house door.\nEnter your name:");
fflush(stdout);
if (fgets(buf, sizeof(buf), stdin))
{
char *p = strchr(buf, '\n');
if (p) *p = '\0';
if (strcmp(Owner, buf) == 0)
printf ("Welcome home %s\n", Owner);
else
printf ("Agghh, who let %s in here?!\n", buf);
}
return 0;
}
/*
* Output:
You are at the house door.
Enter your name:Hammer
Welcome home Hammer
---
You are at the house door.
Enter your name:Trouble
Agghh, who let Trouble in here?!
*
*/
This next example shows how to use strncpy() to compare the first few characters of the arrays, rather than all of them.
#include <stdio.h>
#include <string.h>
int main(void)
{
char *foo = "hello";
char *bar = "help me";
if (strncmp(foo, bar, 3) == 0)
puts("First 3 chars are equal");
else
puts("First 3 chars are NOT equal");
return 0;
}
/*
* Output
First 3 chars are equal
*
*/
From: www.Cprogramming.com