C/C++ strncmp - String Compare n Characters
strcmp() - String Compare strcpy() - String Copy strcat() - String Concatenate
strncmp in C,C++ Programming - Syntax
strncmp is similar to strcmp() but the only difference is that it compares the characters up to the specified length.
Syntax: int strncmp(const char *s1,const char *s2,size_t number);
- strncmp returns zero value if both strings are same.
- strncmp returns negative value if string s1 is less than s2.
- strncmp returns positive value if s1 is greater than s2.
Example C, C++ program using strncmp()
#include<stdio.h>
#include<string.h>
main()
{
char first[]={’W’,‘E’,‘L’,‘C’, ‘O’,‘M’,‘E’};
char second[];
int result;
clrscr();
printf(" The first string is %s ",first);
printf(" \n Enter the second string ");
scanf(" %s ",&second);
result = strncmp(first,second,3 );
if(result==0)
{
printf(" \n The two strings are same upto 3 characters");
}
else
{
printf(" \n The two strings are different");
}
return(0);
}
Output if the input is WELCO:
The first string is WELCOME Enter the second string WELCO The two strings are same upto 3 characters
Output if the input is WE:
The first string is WELCOME Enter the second string WE The two strings are different
strlen() - String Length strlwr() - String Lower
strncat() - String n Concatenate strncpy() - String n Copy
strcat() - String Concatenation strcmp() - String Compare
strcpy() - String Copy strlen() - String Length