Comparing strings in C

String library in C, <cstring> or <string.h> provides several functions to manipulate C strings and arrays. The strcmp() function compares two strings. The function returns 0 if both the strings are equal. The standard form of the strcmp() function is:

int strcmp (const char * str1, const char * str2);

The function compares the string character by character because C treats strings as characters of array.

The return values of strcmp() are either 0, >0 or <0 depending upon string comparison.

Use of strcmp() function

The following C program checks user’s password and terminates when a correct password is entered.

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

int main ()
{
  char password[] = "123xyz";

  char input[10];
  
  do {
     printf ("What is your password? ");
     fflush (stdout);
     scanf ("%s",input);
  } 
  while (strcmp (password,input)!=0);
  
  puts ("Password is correct!");
  
  return 0;
}

The output of the program can be as below:

What is your password? abcxyz

What is your password? 123456

What is your password? 123xyz

Password is correct!

Other String Comparison Functions

memcmp() – Compare two blocks of memory referenced by pointers.

strcoll() – Compare two strings using locale i.e. C localization library

strncmp() – Compare characters of two strings up to a certain number.

strxfrm() – Transform string using locale i.e. C localization library

Categories: Blog
M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post