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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #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:
1 2 3 4 5 6 7 | 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