The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs
strncmp() is one of the inbuilt string function in c programming which is used to compare two strings up to specified length, if the strings are same up to specified length, it returns 0. Otherwise it returns a nonzero value.
The following diagram clearly illustrate the working principle of strncmp() inbuilt string function in C.
In the above diagram, strncmp() compares first n characters of two strings.
strncmp(str1, str2, n);
Let us work through strncmp() function, In the following program we will compare two strings up to specified length n.
#include <stdio.h> #include<string.h> int main() { char str1[20] = "this is strncmp", str2[20] = "this is awesome"; if(strncmp(str1, str2, 8) == 0) printf("The strings str1 and str2 are same up to 8 characters "); return 0; }
The strings str1 and str2 are same up to 8 characters
The above program defines the function strncmp(), which is used to compare two strings up to specified length. Here, str1 and str2 are same up to 8 characters, so it returns 0 and prints the statement inside the condition.
Let us compare two strings up to specified length without using any inbuilt string functions.
#include <stdio.h> #include<string.h> int main() { char str1[20] = "thi is strcmp"; char str2[20] = "this is strcmp"; int n=4, i, j=0; for(i=0; i<n; i++){ if(str1[i] == str2[i]) j++; } if(n == j) printf("The strings str1 and str2 are equal"); else printf("The string str1 and str2 are unequal"); return 0; }
The string str1 and str2 are unequal
The above program looks verbose but yields the same result.
We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.
© Copyright 2019