strncmp function compares two strings
Syntax
C strncmp function has the following syntax.
int strncmp(const char *str1, const char *str2, size_t count);
Header
C strncmp function is from header file string.h.
Description
C strncmp function lexicographically compares not more than count characters and returns an integer as follows:
Value | Meaning |
---|---|
<0 | str1 is less than str2 |
0 | str1 is equal to str2 |
>0 | str1 is greater than str2 |
If there are less than count characters in either string, the comparison ends when the first null is encountered.
Example
Use C strncmp function to compare two strings.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* ww w.j a v a2 s .c om*/
int main(int argc, char *argv[])
{
if(!strncmp("asdfasdfasdfasdf", "asdfasdffdsaasdf", 8))
printf("The strings are the same.\n");
return 0;
}
The code above generates the following result.
Using strcmp and strncmp
#include <stdio.h>
#include <string.h>
/*from w ww.jav a 2 s .c o m*/
int main()
{
const char *s1 = "asdfasdfasdf";
const char *s2 = "fdafdsafdsa";
const char *s3 = "abced";
printf("%s%s\n%s%s\n%s%s\n\n%s%2d\n%s%2d\n%s%2d\n\n",
"s1 = ", s1, "s2 = ", s2, "s3 = ", s3,
"strcmp(s1, s2) = ", strcmp( s1, s2 ),
"strcmp(s1, s3) = ", strcmp( s1, s3 ),
"strcmp(s3, s1) = ", strcmp( s3, s1 ) );
printf("%s%2d\n%s%2d\n%s%2d\n",
"strncmp(s1, s3, 6) = ", strncmp( s1, s3, 6 ),
"strncmp(s1, s3, 7) = ", strncmp( s1, s3, 7 ),
"strncmp(s3, s1, 7) = ", strncmp( s3, s1, 7 ) );
return 0;
}
The code above generates the following result.