Standards / Extensions | C or C++ | Dependencies |
---|---|---|
ISO C |
both |
#include <string.h>
int strncmp(const char *string1, const char *string2, size_t count);
The strncmp() built-in function compares at most the first count characters of the string pointed to by string1 to the string pointed to by string2.
The string arguments to the function should contain a NULL character (\0) marking the end of the string.
The relation between the strings is determined by the sign of the difference between the values of the leftmost first pair of characters that differ. The values depend on character encoding. This function is not locale sensitive.
⁄* CELEBS45
This example demonstrates the difference between &strcmp.
and &strncmp..
*⁄
#include <stdio.h>
#include <string.h>
#define SIZE 10
int index = 3;
int main(void)
{
int result;
char buffer1[SIZE] = "abcdefg";
char buffer2[SIZE] = "abcfg";
void print_result( int, char *, char * );
result = strcmp( buffer1, buffer2 );
printf( " strcmp: compares each character\n");
print_result( result, buffer1, buffer2 );
result = strncmp( buffer1, buffer2, index);
printf( "\nstrncmp: compares only the first %i characters\n", index );
print_result( result, buffer1, buffer2 );
}
void print_result( int res, char * p_buffer1, char * p_buffer2 )
{
if ( res == 0 )
printf( "first %i characters of \"%s\" is identical to \"%s\"\n",
index, p_buffer1, p_buffer2);
else if ( res < 0 )
printf( "\"%s\" is less than \"%s\"\n", p_buffer1, p_buffer2 );
else
printf( "\"%s\" is greater than \"%s\"\n", p_buffer1, p_buffer2 );
}
strcmp: compares each character
"abcdefg" is less than "abcfg"
strncmp: compares only the first 3 characters
first 3 characters of "abcdefg" is identical to "abcfg"