strncmp() Function
The strncmp()
function in C compares two strings character by character up to a specified limit, returning an integer that indicates whether one string is less than, equal to, or greater than the other. The comparison stops when a difference is found, a terminating null-character is reached, or when the specified number of characters has been compared.
Syntax of strncmp()
int strncmp(const char *str1, const char *str2, size_t num);
Parameters
Parameter | Description |
---|---|
str1 | C string to be compared. |
str2 | C string to be compared. |
num | Maximum number of characters to compare. (size_t is an unsigned integral type.) |
Return Value
The function returns an integer that indicates the relationship between the compared segments of the strings: a value less than zero if the first differing character in the first string is less than that in the second, zero if both strings are equal for the specified number of characters, and a value greater than zero if it is greater.
It is important to note that strncmp()
performs a lexicographical comparison based on the ASCII values of the characters and stops processing as soon as a difference is encountered or a null-character is reached.
Examples for strncmp()
Example 1: Comparing Two Identical Strings
This example demonstrates how strncmp()
returns 0 when two strings are identical for the specified number of characters.
Program
#include <stdio.h>
#include <string.h>
int main() {
const char *s1 = "Hello, World!";
const char *s2 = "Hello, World!";
int result;
// Compare the two strings for the first 13 characters
result = strncmp(s1, s2, 13);
printf("Result of comparison: %d\n", result);
return 0;
}
Explanation:
- Two identical C strings are defined.
strncmp()
compares the first 13 characters.- Since all compared characters match, the function returns 0.
- The result is printed to confirm that the strings are equal.
Output:
Result of comparison: 0
Example 2: Comparing Strings with Differences
This example shows how strncmp()
returns a non-zero value when the strings differ within the compared range.
Program
#include <stdio.h>
#include <string.h>
int main() {
const char *s1 = "Hello, World!";
const char *s2 = "Hello, There!";
int result;
// Compare the two strings for the first 12 characters
result = strncmp(s1, s2, 12);
printf("Result of comparison: %d\n", result);
return 0;
}
Explanation:
- Two C strings that differ in content are defined.
strncmp()
is used to compare the first 12 characters.- The function detects a difference between the strings within this range and returns a non-zero value.
- The result is printed to indicate that the strings are not equal in the compared segment.
Output:
Result of comparison: -?[non-zero value]