C library functions -strncmp()
C Standard Library - <string.h>
Description
strncmp()is a standard library function used to compare the firstnwhether the characters are equal.
strncmp()The function is typically used to compare two strings to determine whether they are equal or which string is lexicographically smaller.
C Library Functionsint strncmp(const char *str1, const char *str2, size_t n)holdstr1andstr2for comparison, comparing at most the firstncharacters.
Declaration
Below is the declaration of the strncmp() function.
int strncmp(const char *str1, const char *str2, size_t n)
Parameter
- str1-- The first string to be compared.
- str2-- The second string to be compared.
- n-- the maximum number of characters to compare.
Return Value
The function returns the following values:
- If the return value < 0, it indicates that str1 is less than str2.
- If the return value > 0, it indicates that str1 is greater than str2.
- If the return value = 0, it indicates that str1 is equal to str2.
Example
The following example demonstrates the usage of the strncmp() function.
Example
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[15];
char str2[15];
int ret;
strcpy(str1, "abcdef");
strcpy(str2, "ABCDEF");
ret = strncmp(str1, str2, 4);
if(ret < 0)
{
printf("str1 is less than str2");
}
else if(ret > 0)
{
printf("str2 is less than str1");
}
else
{
printf("str1 is equal to str2");
}
return(0);
}
#include <string.h>
int main ()
{
char str1[15];
char str2[15];
int ret;
strcpy(str1, "abcdef");
strcpy(str2, "ABCDEF");
ret = strncmp(str1, str2, 4);
if(ret < 0)
{
printf("str1 is less than str2");
}
else if(ret > 0)
{
printf("str2 is less than str1");
}
else
{
printf("str1 is equal to str2");
}
return(0);
}
Let us compile and run the above program, which will produce the following result:
str2 小于 str1other extensions