strncmp
The strncmp
function in C is used to compare two strings up to a specified number of characters. It returns an integer value that indicates the relationship between the two strings.
Syntax:
The syntax of strncmp
is as follows:
int strncmp(const char str1, const char str2, size_t n);
str1
andstr2
are the strings to be compared.n
is the maximum number of characters to compare.
Explanation of Steps:
- The
strncmp
function compares the characters ofstr1
andstr2
up to the specified number of charactersn
. - It returns an integer value based on the comparison:
- If the two strings are equal up to
n
characters, it returns 0. - If
str1
is less thanstr2
, it returns a negative value. - If
str1
is greater thanstr2
, it returns a positive value.
Example:
Here's an example that demonstrates the usage of strncmp
:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "Help";
int result = strncmp(str1, str2, 3);
if (result == 0) {
printf("The strings are equal.\n");
} else if (result < 0) {
printf("str1 is less than str2.\n");
} else {
printf("str1 is greater than str2.\n");
}
return 0;
}
Output:
The strings are equal.