0Pricing
C Academy · Lesson

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 a is less than in b
  • 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

  1. strlen, strcpy, strcat
  2. strcmp and Comparison
  3. strtok and Tokenizing
  4. memcpy and memset
← Back to C Academy