strcmp() Function in C: Comparing Strings

Rumman Ansari   Software Engineer   2024-07-05 04:23:07   8117  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

strcmp() function in C compares two given strings and returns zero if they are same.

Syntax

int strcmp(const char *strng1, const char *strng2);

The strcmp( ) function lexicographically compares two strings and returns an integer based on the outcome as shown here:

Parameters

strng1 -first string
strng2 -Second string

Returns

Return Value Description
Less than zero  strng1 is less than strng2
Zero strng1 is equal to strng2
Greater than zero strng1 is greater than strng2

Program 1

 #include 
#include 
int main( )
{
   char str1[ ] = "atnyla" ;
   char str2[ ] = "atNyla" ;
   int i, j, k, l;
   i = strcmp ( str1, "feel" ) ;
   j = strcmp ( str1, str2 ) ;
   k = strcmp ( str1, "f" ) ;
   l = strcmp ( str1, str1 ) ;
   printf ( "\n%d %d %d %d\n", i, j, k,l ) ;
   return 0;
}

Output

 
 
-1 1 -1 0
Press any key to continue . . .

Program 2

You can use the following function as a password-verification routine. It returns zero on failure and 1 on success. Here your predefined password is "pass"

 #include 
#include 
int main( )
{
 int a;
 a = password();
 if(a==1)
 {
 printf("password matched\n");
 }
}

int password(void)
{
	char s[80];
	printf("Enter password: ");
	gets(s);
	if(strcmp(s, "pass")) {
	printf("Invalid Password\n");
	
	return 0;
	}
return 1;
}

Output

 
Output 1
Enter password: pass
password matched
Press any key to continue . . .

Output 2 
Enter password: passwo
Invalid Password
Press any key to continue . . .

Point to be noted

strcmp() function is case sensitive. i.e, "A" and "a" are treated as different characters.



Stay Ahead of the Curve! Check out these trending topics and sharpen your skills.