CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

C Programming – How to compare strings?

C library has string functions to compare whether the given strings are identical or not.

strcmp library function

This function takes two arguments, both are strings. Compare the strings and return 0 if the strings are identical; otherwise, this function returns a non-zero value.

What is the meaning of non-zero value? When the first string is less than the second string it returns the negative value. If the first string is greater than the second string it will return a positive value.

The syntax of the function looks like below;

int strcmp (const char *s1, const char *s2);

Note that the comparison is case-sensitive. That means the strings “Library” & “library” are not identical.

Let’s pass these strings and observe the results.

 printf("%d", strcmp("Library", "library"));

It returns the value -32, which is a negative value; it means the first string is less than the second string. But, why the value -32? Let’s dig a little bit deep into the function.

When this function compares the strings, it compares each character from the two strings. It takes the first character “L” from the first string and compares it with the first character “l” in the second string. Note that, the ASCII value of ‘L’ is 76 and ‘l’ is 108, and the difference here is -32. As both these characters are not the same, it stops the comparison and returns the difference between the two characters, in this case, it is -32.

strncmp library function

This is the same as strcmp function. The only difference is, that it takes three arguments, and compares n bytes of the first string to the second string. The syntax of the function looks like the below;

int strncmp (const char *s1, const char *s2, size_t n);

It returns the value 0 if both the strings are identical. Otherwise, it returns a non-zero value.

stricmp library function

To do the case-insensitive comparison we can use stricmp function. The syntax of the function is similar to the strcmp function. It looks like the below;

int stricmp (const char *s1, const char *s2);

This function compares two strings and returns the value 0 if the strings are identical. Otherwise, it returns the non-zero value. The comparison is case-insensitive. That means strings “WORLD” & “world” are identical strings.

strcmpi library function

This function is the same as stricmp function.

int strcmpi (const char *s1, const char *s2);

NOTE that, stricmp & strcmpi are nonstandard C library functions. You may not see these functions in your C library.

// Malin

C Programming – How to compare strings?

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top