C - String String Comparing


strcmp(str1, str2) compares two strings, str1 and str2.

It returns a value of type int that is less than, equal to, or greater than 0, depending on whether str1 is less than, equal to, or greater than str2.

char str1[] = "The quick brown fox";
char str2[] = "The quick black fox";
if(strcmp(str1, str2) > 0)
  printf("str1 is greater than str2.\n");

The printf() statement will execute only if the strcmp() function returns a positive integer when the character code in str1 is greater than the character code in str2.

strncmp() function compares up to a given number, n, of characters of the two strings.

You can use the strncmp() function to compare the first ten characters of two strings to determine which should come first:

if(strncmp(str1, str2, 10) <= 0)
  printf("\n%s\n%s", str1, str2);
  printf("\n%s\n%s", str2, str1);


The following code compares just two words that you enter from the keyboard.

This example will introduce a safer alternative to the scanf() function for keyboard input, scanf_s(), which is declared in stdio.h:


#define __STDC_WANT_LIB_EXT1__ 1                    // Make optional versions of functions available
#include <stdio.h>
#include <string.h>

#define MAX_LENGTH 21                               // Maximum char array length
int main(void)
  char word1[MAX_LENGTH];                           // Stores the first word
  char word2[MAX_LENGTH];                           // Stores the second word

  printf("Type in the first word (maximum %d characters): ", MAX_LENGTH - 1);
  int retval = scanf_s("%s", word1, sizeof(word1)); // Read the first word
  if (EOF == retval)
  {//  ww w  . j a v  a 2  s.c  o m
    printf("Error reading the word.\n");
    return 1;

  printf("Type in the second word (maximum %d characters): ", MAX_LENGTH - 1);
  retval = scanf_s("%s", word2, sizeof(word2));     // Read the second word
  if (EOF == retval)
    printf("Error reading the word.\n");
    return 2;
  // Compare the words
  if (strcmp(word1, word2) == 0)
    printf("You have entered identical words");
    printf("%s precedes %s\n",
    (strcmp(word1, word2) < 0) ? word1 : word2,
      (strcmp(word1, word2) < 0) ? word2 : word1);
  return 0;


Related Topics