Understanding String Comparison in C: strcmp() vs. strnicmp()
strcmp() and stricmp() :
strcmp() function is useful to compare two strings. While comparing, it will take the case of the strings into considertation. To compare s1 and s2 strings.
int n = strcmp(s1,s2);
/* if s1 and s2 are same, strcmp() returns zero */
if s1 == s2, n == 0;
/* if s1 comes after s2, then it returns a positive value */
if s1 > s2, n = +ve
/* if s1 comes after s2, then it returns a positive value */
if s1 < s2, n= -ve
Example: strcmp (“jerry”, “jerry”) returns 0
strcmp (“jerry”, “ferry”) returns some positive number
strcmp (“jerry”, “merry”) returns some negative number stricmp() is case insensitive. This means stricmp() will compare two strings without regarding their case.
Example: strcmp(“jerry”,”JERRY”) returns positive number.
stricmp(“jerry”, “JERRY”) returns 0;
strncmp() and strnicmp():
strncmp() function compares first n characters of two strings. It returns an integer number. This function is case sensitive.
int n = strncmp(s1, s2. num);
Here, ‘num’ represents number of characters being compared from s1 and s2.
/* if parts of s1 and s2 are same, it returns 0 */
if s1 == s2, n == 0;
/* if part of s1 comes after s2, it returns a positive value */
if s1 > s2, n = +ve
/* if parts of s1 comes before s2, then it returns a negative value */
if s1 < s2, n= -ve
strnicmp() it works same as strncmp() but it does not take case into consideration.