C

Example Of The C Strncmp() Function

In the previous tutorial, we looked at the strcmp() function, which is used to compare two strings. This guide will go over the strncmp() function, which is similar to strcmp() except that the strncmp() comparison is limited to the number of characters specified during the function call. Strncmp(str1, str2, 4) would, for example, compare only the first four characters of strings str1 and str2.

Function declaration in C strncmp()

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

str1 is the first string.
str2 stands for Second String.
n – the number of characters to be compared.

Strncmp’s return value ()

This function compares only the first n (specified number of) characters of a string and returns the resulting value.
>0, if the ASCII value of the first unmatched character of str1 is greater than str2 0, if the ASCII value of the first unmatched character of str1 is less than str2

Example 1: The C strncmp() function

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

int main () {
   char str1[20];
   char str2[20];
   int result;

   //Assigning the value to the string str1
   strcpy(str1, "hello");

   //Assigning the value to the string str2
   strcpy(str2, "helLO WORLD");

   //This will compare the first 3 characters
   result = strncmp(str1, str2, 3);

   if(result > 0) {
      printf("ASCII value of first unmatched character of str1 is greater than str2");
   } else if(result < 0) {
      printf("ASCII value of first unmatched character of str1 is less than str2");
   } else {
      printf("Both the strings str1 and str2 are equal");
   }

   return 0;
}

Output:

Both the strings str1 and str2 are equal

Example No. 2 of the strncmp() function

Let us alter the preceding example slightly. We’re comparing the first four characters of strings here.

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

int main () {
   char str1[20];
   char str2[20];
   int result;

   strcpy(str1, "hello");
   strcpy(str2, "helLO WORLD");

   //This will compare the first 4 characters
   result = strncmp(str1, str2, 4);

   if(result > 0) {
      printf("ASCII value of first unmatched character of str1 is greater than str2");
   } else if(result < 0) {
      printf("ASCII value of first unmatched character of str1 is less than str2");
   } else {
      printf("Both the strings str1 and str2 are equal");
   }

   return 0;
}

Output:

ASCII value of first unmatched character of str1 is greater than str2

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button