How To Compare String In C?

C programming language provides the strcmp() function in order to compare strings. Strings are represented as character or char arrays in C. In this tutorial, we examine how to compare strings in C programming.

strcmp() Function Syntax

The strcmp() function syntax is like below.

int strcmp(const char* STR1, const char* STR2)
  • STR1 is the first string.
  • STR2 is the second string.

If strings are equal the strcmp() function returns 0.

If strings are not equal and the first non-matching character of STR1 is greater than STR2 positive number is returned.

If strings are not equal and the first non-matching character of STR2 is greater than STR1 negative number is returned.

Compare Strings

In the following example, we compare 3 strings called “wisetut”,”wisetut” and “wisepof”. The results are printed on the terminal.

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

int main() {
  char str1[] = "wisetut", str2[] = "wisetut", str3[] = "wisepof";
  int result;

  // comparing strings str1 and str2
  result = strcmp(str1, str2);
  //result is 0 as two string is equal or identical
  printf("strcmp(str1, str2) = %d\n", result);

  // comparing strings str1 and str3
  result = strcmp(str1, str3);
  //result is negative as they are not identical the character "p" is greater than "t"
  printf("strcmp(str1, str3) = %d\n", result);

  return 0;
}

Compare Input Strings

In the following example, we get the strings as inputs by using the scanf() function. Then these strings are compared.

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

int main() {
  char str1[20] , str2[20] = , str3[20];
  int result;

  scanf("%s",str1);
  scanf("%s",str2);
  scanf("%s",str3);

  // comparing strings str1 and str2
  result = strcmp(str1, str2);
  printf("strcmp(str1, str2) = %d\n", result);

  // comparing strings str1 and str3
  result = strcmp(str1, str3);
  printf("strcmp(str1, str3) = %d\n", result);

  return 0;
}

Leave a Comment