C string library function strcmp() and strncmp()


In this article, you will learn the concept and use of C string library function strcmp() and strncmp() that are defined in string handling library <string.h>.

C string library function strcmp() and strncmp()

These are built in functions of C programming string handling library for string comparison.

Function prototype of C string library function strcmp() and strncmp()

int strcmp( const char *str1, const char *str2 );
int strncmp( const char *str1, const char *str2, size_t n );

where str1 and str2 two strings for comparison.

Function strcmp compares the string str1 with str2. It returns zero if str1 is equal to str2 otherwise less than zero or greater than zero if str1 is less than or greater than str2, respectively.

Function strncmp compares up to n characters of the string str1 with str2. The return value of strncmp is same as strcmp.

The positive and negative value returned by strncmp function is the numeric difference between the first nonmatching characters in the strings.

The str1 and str2 may be character array variable or string constants.

For example:

strcmp( str1, str2);
strcmp( str1, "Hello");
strcmp( "Hello", "World");

Example: C program to demonstrate the function of strcmp() and strncmp()

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

int main()
{
   char str1[ ] = "trytoprogram"; //initialize character array
   char str2[ ] = "trytoprogram"; //initialize character array
   char str3[ ] = "tryforprogram"; //initialize character array

   printf("str1 = %s\n"
          "str2 = %s\n"
          "str3 = %s\n\n", str1, str2, str3);

   //comparing strings
   printf("strcmp(str1, str2) = %d\n", strcmp(str1, str2));
   printf("strcmp(str2, str3) = %d\n", strcmp(str2, str3));
   printf("strcmp(str3, str1) = %d\n\n", strcmp(str3, str1));

   //comparing n characters
   printf("strncmp(str1, str3, 3) = %d\n", strncmp(str1, str3, 3));
   printf("strncmp(str1, str3, 6) = %d\n", strncmp(str1, str3, 6));
   printf("strncmp(str3, str1, 6) = %d\n\n", strncmp(str3, str1, 6));

   return 0;
}

Output

c strcmp strncmp output

Explanation

In the above program, there is a comparison between str1, str2 and str3.

strcmp(str1, str2) compares both string character-wise and returns integer value as shown in the output.

As we can see that, strncmp(str1, str3, 6) returns integer value 14.

You may be wondering why it returns 14 not other integer value. Let’s dig a bit dipper:

All characters in the alphabet are represented by integer value known as ASCII value.

While comparing two strings "trytoprogram" and "tryforprogram", the difference is at 3rd position. i.e. "t" and “f”

ASCII value of "t" = 116

ASCII value of "f" = 102

The difference is 114 and hence the output.