Skip to content

C – strcmp( ) function – Compare Strings

by yashan on April 20th, 2012

Strcmp() in C programming language is used to compare two strings. If both the strings are equal then it gives the result as zero but if not then it gives the numeric difference between the first non matching characters in the strings. Syntax of C strcmp() function is–

   strcmp(string1,string2);

String1 and string2 may be string variables or string constants. Examples of c strcmp() function are –

   strcmp(name1,name2);
   strcmp(name1,”JOHN”);
   strcmp(“ROM”,”RAM”);

This function is mainly used to compare whether the strings are equal or not. The value of the mismatch is rarely important. For example, the statement –

   strcmp(“their”,”there”);

Will return the value of -9 which is numeric difference between ASCII “i” and ASCII “r”. That is, “i” minus “r” in ASCII code is -9. If the value is negative, string1 is alphabetically above string2.

C Program to check if the two strings are equal or not

/* Sample C program for the strcmp function*/
#include<stdio.h>
#include<conio.h>
#include<string.h>

void main()
{
     char nm[20],nm2[20];
     clrscr();
     
     puts("Enter a string - ");
     gets(nm);
     puts("Enter another string to know if both the strings are equal");
     gets(nm2);
     
     if(strcmp(nm,nm2)==0)
     {
           printf("Both the strings are equal");
     }
     else
     {
         printf("Strings are not equal");
     }
     getch();
}

Input -
Enter first string – hello
Enter second string – world
Case 2 -
First string – hello
second string – hello

Output –
String are not equal
Case 2 – Both strings are equal

From → C Tutorials

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS