Loading, please wait...

Comparison Functions

This section presents the string-handling library’s string-comparison functions, strcmp and strncmp.

 

Following table contains their prototypes and a brief description of each function.

 

Function prototype

Function Description

int strcmp( const char *s1, const char *s2 );

Compares the string s1 with the string s2. The function returns 0,

less than 0 or greater than 0 if s1 is equal to, less than or greater than s2, respectively.

int strncmp( const char *s1, const char *s2, size_t n );

Compares up to n characters of the string s1 with the string s2. The function returns 0, less than 0 or greater than 0 if s1 is equal to, less than or greater than s2, respectively.

 

 

Functions strcmp and strncmp

Following Example compares three strings using strcmp and strncmp. Function strcmp compares its first string argument with its second string argument, character by character. The function returns 0 if the strings are equal, a negative value if the first string is less than the second string and a positive value if the first string is greater than the second string.

 

Function strncmp is equivalent to strcmp, except that strncmp compares up to a specified number of characters. Function strncmp does not compare characters following a null character in a string. The program prints the integer value returned by each function call.

 

Example:

/* How to use strcmp and strncmp */

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

int main( void )
{
const char *s1 = "Happy New Year"; /* initialize char pointer */
const char *s2 = "Happy New Year"; /* initialize char pointer */
const char *s3 = "Happy Holidays"; /* initialize char pointer */
printf("%s%s\n%s%s\n%s%s\n\n%s%2d\n%s%2d\n%s%2d\n\n",
"s1 = ", s1, "s2 = ", s2, "s3 = ", s3,
"strcmp(s1, s2) = ", strcmp( s1, s2 ),
"strcmp(s1, s3) = ", strcmp( s1, s3 ),
"strcmp(s3, s1) = ", strcmp( s3, s1 ),

printf("%s%2d\n%s%2d\n%s%2d\n",
"strncmp(s1, s3, 6) = ", strncmp( s1, s3, 6 ),
"strncmp(s1, s3, 7) = ", strncmp( s1, s3, 7 ),
"strncmp(s1, s3, 7) = ", strncmp( s1, s3, 7 ),
.
return 0;
}

Output:

s1 = Happy New Year

s2 = Happy New Year

s3 = Happy Holidays



strcmp(s1, s2) = 0

strcmp(s1, s3) = 1

strcmp(s3, s1) = -1



strncmp(s1, s3, 6) = 0

strncmp(s1, s3, 7) = 6

strncmp(s3, s1, 7) = -6