C strcmp() Function
strcmp() compares two strings character by character.
Return value
| Result | Meaning |
|---|---|
| 0 | Both strings are equal |
| Less than 0 | First string comes before the second |
| Greater than 0 | First string comes after the second |
#include <stdio.h>
#include <string.h>
int main(void) {
printf("%d\n", strcmp("apple", "apple") == 0);
printf("%d\n", strcmp("apple", "banana") < 0);
printf("%d\n", strcmp("cat", "Cat") > 0);
return 0;
}
Output:
Output of the above program is
1
1
1
The first line is 1 because the strings are equal. The second is 1 because “apple” comes before “banana”. The third is 1 because lower case letters have a bigger ASCII code than capital letters, so “cat” comes after “Cat”. The comparison is case sensitive.
Check a password
#include <stdio.h>
#include <string.h>
int main(void) {
char input[] = "secret123";
if (strcmp(input, "secret123") == 0) {
printf("Access granted\n");
} else {
printf("Wrong password\n");
}
return 0;
}
Output:
Output of the above program is
Access granted
Why not use ==
input == "secret123" compares the addresses of two arrays, not the text. It is almost always false. Always use strcmp() for strings.
Note:
The exact positive or negative number can be different on each system. Check only for zero, less than zero or more than zero.
Next: C strstr() Function.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |