strncmp function in C Programming

4 years, 6 months ago C Programming

To understand this topic clearly, you should understand the strcmp function in C programming firstly. If you have understood already, then go ahead.

strncmp function is  a variation of strcmp function. It compares a certain amount of characters of two null-terminated byte strings. The basic form is given below:

strncmp(str1, str2, n);

Here str1, str2 & n are the three parameters of this function. str1 & str2 are two null-terminated byte strings and n is an integer. n indicates the left-most n characters of str1. If str2 & the substring of str1 are equal, then strncmp function returns the value 0. Otherwise, it returns a numeric difference between the first mismatching characters based on ASCII value. If the value is negative, the substring of str1 is less than str2. If positive, the opposite result occurs. Now take a look at this example:

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

int main()
{
 int i;
 char str1[15] = "Bangladesh";
 char str2[15] = "Bangla";
 if(strncmp(str1, str2, 6) == 0){
 printf("Match\n");
 }
 else{
 printf("Mismatch\n");
 }
 if(strncmp("Coder", "Coding", 3) == 0){
 printf("Match\n");
 }
 else{
 printf("Mismatch\n");
 }
 return 0;
}

Output:

Match

Match

I think now the use of this function is clear to you. I hope from now you will use strncmp function to compare substrings. If you have any question, just shout in the comment box given below. Happy Coding!!!

Previous Next
Comments
Have you read the comment guideline?

Give me useful, constructive criticism. Spot a typo or an error? Let me know and I will correct it.