In the last tutorial we discussed strcmp() function which is used for comparing two strings. In this guide, we will discuss strncmp() function which is same as strcmp(), except that strncmp() comparison is limited to the number of characters specified during the function call. For example strncmp(str1, str2, 4) would compare only the first four characters of strings str1 and str2.
C strncmp() function declaration
int strncmp(const char *str1, const char *str2, size_t n)
str1 – First String
str2 – Second String
n – number of characters that needs to be compared.
Return value of strncmp()
This function compares only the first n (specified number of) characters of strings and returns following value based on the comparison.
- 0, if both the strings str1 and str2 are equal
- >0, if the ASCII value of first unmatched character of str1 is greater than str2
- <0, if the ASCII value of first unmatched character of str1 is less than str2
Example 1: strncmp() function in C
#include <stdio.h> #include <string.h> int main () { char str1[20]; char str2[20]; int result; //Assigning the value to the string str1 strcpy(str1, "hello"); //Assigning the value to the string str2 strcpy(str2, "helLO WORLD"); //This will compare the first 3 characters result = strncmp(str1, str2, 3); if(result > 0) { printf("ASCII value of first unmatched character of str1 is greater than str2"); } else if(result < 0) { printf("ASCII value of first unmatched character of str1 is less than str2"); } else { printf("Both the strings str1 and str2 are equal"); } return 0; }
Output:
Both the strings str1 and str2 are equal
Example 2 of strncmp() function
Lets change the above example a little bit. Here we are comparing the first four characters of strings.
#include <stdio.h> #include <string.h> int main () { char str1[20]; char str2[20]; int result; strcpy(str1, "hello"); strcpy(str2, "helLO WORLD"); //This will compare the first 4 characters result = strncmp(str1, str2, 4); if(result > 0) { printf("ASCII value of first unmatched character of str1 is greater than str2"); } else if(result < 0) { printf("ASCII value of first unmatched character of str1 is less than str2"); } else { printf("Both the strings str1 and str2 are equal"); } return 0; }
Output:
ASCII value of first unmatched character of str1 is greater than str2
Leave a Reply