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 and str2 are the strings to be compared.
  • n is the maximum number of characters to compare.

Explanation of Steps:

  1. The strncmp function compares the characters of str1 and str2 up to the specified number of characters n.
  2. It returns an integer value based on the comparison:
  3. If the two strings are equal up to n characters, it returns 0.
  4. If str1 is less than str2, it returns a negative value.
  5. If str1 is greater than str2, 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.