CodeBlanks Logo Icon CodeBlanks

strcmp

Learn to compare two strings with strcmp.

Comparing strings with strcmp

You cannot compare two strings with ==; that compares addresses. Instead, use strcmp.

int result = strcmp("apple", "apple");
/* result = 0: equal */
int diff = strcmp("apple", "banana");
/* diff < 0: "apple" is smaller */

strcmp returns negative, zero, or positive. Zero means the strings are equal. Comparison is based on ASCII values of characters.

ASCII ordering

strcmp compares based on ASCII values of characters. Uppercase comes before lowercase: 'A'=65, 'a'=97. So strcmp("Apple", "apple") returns negative.

strcmp("Banana", "Banana");  /* 0 */
strcmp("Banana", "apple");   /* negative */
strcmp("apple", "Banana");   /* positive */

The comparison is case-sensitive. To test equality, check if the result is == 0.

Practice Compare two passwords

Define two char arrays: "pass123" and "pass123". Compare them with strcmp and print the result with printf %d. The result should be 0; output should be 0.

Starter code

main.c
#include <stdio.h>
#include <string.h>

int main(void) {
    /* define two char arrays */
    /* compare with strcmp and print with printf %d */
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <string.h>

int main(void) {
    char a[] = "pass123";
    char b[] = "pass123";
    int r = strcmp(a, b);
    printf("%d\n", r);
    return 0;
}

Expected output

0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 strcmp return values

Term Meaning
0 strings equal
negative first is smaller
positive first is larger
== compares addresses

2 What does `strcmp("apple", "apple")` return?

main.c
int r = strcmp("apple", "apple");
  • -1
  • 2
  • 1
  • 0 Correct answer

Explanation: strcmp returns 0 for equal strings.

3 Equality test

Question
if (strcmp(a, b) ____) { /* strings equal */ }
Answer
if (strcmp(a, b) == 0) { /* strings equal */ }

Explanation: strcmp returns 0 when the strings are equal.

All lessons in Beginner