C memcmp function compares two strings
Syntax
C memcmp function has the following syntax.
int memcmp(const void *buf1, const void *buf2, size_t count);
Header
C memcmp function
is from header file string.h
.
Description
C memcmp function compares the first count characters between buf1
and buf2
.
Return
memcmp returns an integer as follows:
Value | Meaning |
---|---|
< 0 | buf1 is less than buf2 |
0 | buf1 is equal to buf2 |
> 0 | buf1 is greater than buf2 |
Example
Use C memcmp function to compare two strings.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*from ww w . ja v a 2s. c om*/
int main(int argc, char *argv[])
{
int outcome, len, l1, l2;
char *str = "asdf";
char *str1 = "asdfasdf";
/* find the length of shortest string */
l1 = strlen(str);
l2 = strlen(str1);
len = l1 < l2 ? l1:l2;
outcome = memcmp(str, str1, len);
if(!outcome)
printf("Equal");
else if(outcome<0)
printf("First less than second.");
else
printf("First greater than second.");
return 0;
}
The code above generates the following result.