strncmp() function
The strncmp function in C is used to compare a specified number of characters from the beginning of two strings. It is defined in the <string.h> header file.
Purpose:
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
Parameters:
Return Value of 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)
Example
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Computer";
char str2[] = "Compute";
// Compare first 7 characters
int result = strncmp(str1, str2, 7);
if (result == 0)
printf("First 7 characters are same.\n");
else if (result > 0)
printf("str1 is greater than str2.\n");
else
printf("str1 is smaller than str2.\n");
return 0;
}
Output of program:
First 7 characters are same.
No comments:
Post a Comment