The ones who are crazy enough to think they can change the world are the ones who do.
- Steve Jobs

strncmp() In C

Purpose of strncmp()

strncmp() is one of the inbuilt string function in c programming which is used to compare two strings up to specified length, if the strings are same up to specified length, it returns 0. Otherwise it returns a nonzero value.

How strncmp() Works

The following diagram clearly illustrate the working principle of strncmp() inbuilt string function in C.

strncmp() in c

In the above diagram, strncmp() compares first n characters of two strings.

Syntax - strncmp()

  • strcmp() accepts three parameters.
  • First two parameters are strings whereas third parameter is a integer.
  • To use strncmp() inbuilt string function in C, we need to declare #include<string.h> header file.
Syntax
strncmp(str1, str2, n);

C Program - strncmp()

Let us work through strncmp() function, In the following program we will compare two strings up to specified length n.

c-using-strncmp.c
#include <stdio.h>
#include<string.h>
int main()
{
char str1[20] = "this is strncmp", str2[20] = "this is awesome";
if(strncmp(str1, str2, 8) == 0)
printf("The strings str1 and str2 are same up to 8 characters ");
return 0;
}
The strings str1 and str2 are same up to 8 characters

Note:

The above program defines the function strncmp(), which is used to compare two strings up to specified length. Here, str1 and str2 are same up to 8 characters, so it returns 0 and prints the statement inside the condition.

C Program - Without strncmp()

Let us compare two strings up to specified length without using any inbuilt string functions.

c-without-strncmp.c
#include <stdio.h>
#include<string.h>
int main()
{
char str1[20] = "thi is strcmp";
char str2[20] = "this is strcmp";
int n=4, i, j=0;
for(i=0; i<n; i++){
if(str1[i] == str2[i])
j++;
}
if(n == j)
printf("The strings str1 and str2 are equal");
else
printf("The string str1 and str2 are unequal");
return 0;
}
The string str1 and str2 are unequal

Note:

The above program looks verbose but yields the same result.

Report Us

We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.

Report