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