Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case Insensitive String Comparison in C

I have two postcodes char* that I want to compare, ignoring case. Is there a function to do this?

Or do I have to loop through each use the tolower function and then do the comparison?

Any idea how this function will react with numbers in the string

Thanks

like image 750
bond425 Avatar asked Apr 28 '11 15:04

bond425


People also ask

How do you compare strings case insensitive?

The equalsIgnoreCase() method of the String class is similar to the equals() method the difference if this method compares the given string to the current one ignoring case.

Is string compare case-sensitive C?

It is case-insensitive.

What is case insensitive in C?

C Program Case Insensitive String Comparison USING stricmp() built-in string function. /* C program to input two strings and check whether both strings are the same (equal) or not using stricmp() predefined function. stricmp() gives a case insensitive comparison.

Can I use == to compare strings in C?

In C, string values (including string literals) are represented as arrays of char followed by a 0 terminator, and you cannot use the == operator to compare array contents; the language simply doesn't define the operation.


2 Answers

There is no function that does this in the C standard. Unix systems that comply with POSIX are required to have strcasecmp in the header strings.h; Microsoft systems have stricmp. To be on the portable side, write your own:

int strcicmp(char const *a, char const *b) {     for (;; a++, b++) {         int d = tolower((unsigned char)*a) - tolower((unsigned char)*b);         if (d != 0 || !*a)             return d;     } } 

But note that none of these solutions will work with UTF-8 strings, only ASCII ones.

like image 52
4 revs, 2 users 97% Avatar answered Sep 29 '22 13:09

4 revs, 2 users 97%


Take a look at strcasecmp() in strings.h.

like image 41
Mihran Hovsepyan Avatar answered Sep 29 '22 14:09

Mihran Hovsepyan