strncmp
The strncmp function compares two null terminated strings that have been passed as arguments to the function. The comparison is done character by character, and is case sensitive. Different from the strcmp function, however, the comparison is done only for the first n characters, where n is passed as a parameter.
The strcmp function requires three arguments. The first two arguments are pointers to the first and second strings that need to be compared, respectively. If any of the arguments do not point to a valid null terminated string, the result of the function is unpredictable. The third argument is an integer value, which determines how many characters will be compared by the function.
Similar to strcmp, the return value of the strcmp function indicates how the two strings compare using a lexicographic method. If the strings are equal, the return value is zero. If the first string comes before the second string in the lexicographic order, then the value -1 is returned. Otherwise, the value 1 is returned.
The following code shows an example of strncmp in use:
#include <string.h> #include <stdio.h> int main() { char *s1 = "the initial string"; char *s2 = "the second string"; int res; res = strncmp(s1, s2, 10); if (res == 0) printf("the first string is equal to the second\n"); else if (res < 0) printf("the first string is less than the second\n"); else if (res > 0) printf("the second string is less than the first\n"); printf("the value is %d\n", res); res = strncmp(s1, s2, 4); if (res == 0) printf("the first string is equal to the second\n"); else if (res < 0) printf("the first string is less than the second\n"); else if (res > 0) printf("the second string is less than the first\n"); printf("the value is %d\n", res); return 0; }
This code will output the following result:
the first string is less than the second the value is -10 the first string is equal to the second the value is 0
Post a comment