strncmp() function
Purpose:
- Partial String Comparison: strncmp is useful when only a portion of a string needs to be compared, rather than the entire string. This is particularly relevant when dealing with prefixes, command parsing, or verifying specific patterns at the start of a string.
- Bounded Comparison: It provides a safeguard against buffer overflows by limiting the number of characters compared.
The function takes three arguments: two pointers to the strings to be compared (str1 and str2), and an integer n representing the maximum number of characters to compare. It compares characters lexicographically, one by one, from the beginning of each string until "mismatch is found".
Function Syntax
- int strncmp(const char *str1, const char *str2, size_t n);
Parameters:
- str1 → first string
- str2 → second string
- n → number of characters to compare
Return Value of function:
- Zero (0): If the first n characters of both strings are equal.
- Positive value: if first differing character in str1 is greater than that in str2 (difference ASCII value)
- Negative value: if first differing character in str1 is less than that in str2 (difference of ASCII value)