strcmp and Comparison
Comparing strings.
Comparing strings
You cannot compare strings with == in C. That only compares the addresses of two arrays, not their contents.
Use strcmp(a, b) from <string.h> to compare character by character.
#include <stdio.h>
#include <string.h>
int main(void) {
char a[] = "apple";
char b[] = "apple";
if (strcmp(a, b) == 0)
printf("Strings are equal\n");
return 0;
}What strcmp returns
strcmp returns an int:
- 0 if the strings are equal
- a negative value if the first differing char in
ais less than inb - a positive value otherwise
#include <stdio.h>
#include <string.h>
int main(void) {
printf("%d\n", strcmp("abc", "abc"));
printf("%d\n", strcmp("abc", "abd"));
printf("%d\n", strcmp("abd", "abc"));
return 0;
}All lessons in this course
- strlen, strcpy, strcat
- strcmp and Comparison
- strtok and Tokenizing
- memcpy and memset