Format
#include <string.h> int strncmp(const char *string1, const char *string2, size_t count);
Language Level: ANSI, POSIX, XPG4
On both OS/2 and Windows, strncmp compares the first count characters of string1 and string2. If count is greater than the length of string1 or string2, characters that follow a null character are not compared.
Return Value
strncmp returns a value indicating the relationship
between the substrings, as follows:
| Value | Meaning |
| Less than 0 | substring1 less than substring2 |
| 0 | substring1 equivalent to substring2 |
| Greater than 0 | substring1 greater than substring2 |
Example
This example demonstrates the difference between strcmp
and strncmp.
#include <stdio.h> #include <string.h>
#define SIZE 10
int main(void)
{
int result;
int index = 3;
char buffer1[SIZE] = "abcdefg";
char buffer2[SIZE] = "abcfg";
void print_result( int, char *, char * );
result = strcmp( buffer1, buffer2 ); printf( "Comparison of each character\n" ); printf( " strcmp: " ); print_result( result, buffer1, buffer2 );
result = strncmp( buffer1, buffer2, index); printf( "\nComparison of only the first %i characters\n", index ); printf( " strncmp: " ); print_result( result, buffer1, buffer2 ); return 0;
/***************************************************************
The output should be:
Comparison of each character
strcmp: "abcdefg" is less than "abcfg"
Comparison of only the first 3 characters
strncmp: "abcdefg" is identical to "abcfg"
***************************************************************/
}
void print_result( int res, char * p_buffer1, char * p_buffer2 )
{
if ( res == 0 )
printf( "\"%s\" is identical to \"%s\"\n", 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 -- Compare String
strcmpi -- Compare Strings Without
Case Sensitivity
strcspn -- Compare Strings for
Substrings
stricmp -- Compare Strings as
Lowercase
strncat -- Concatenate Strings
strncpy -- Copy Strings
strnicmp -- Compare Strings Without
Case Sensitivity
strpbrk -- Find Characters in String
strrchr -- Find Last Occurrence of
Character in String
strspn -- Search Strings
wcscmp -- Compare Wide-Character
Strings
wcsncmp -- Compare Wide-Character
Strings
<string.h>