[Tip] How to compare strings or char pointers case insensitive in C++?

[Tip] How to compare strings or char pointers case insensitive in C++?

Do you want compare two strings or two char pointers case-insensitive using C++? Here's the most useful and intuitive form I have found to make this comparison.

This way you just need include a standard library for C++: that is, you don't need download anything nor create a new method. Below we'll see some quick examples of how to compare two strings or char pointers by case-insensitive in C++ - but I already must say: it's very simple.

Comparing strings:
#include <strings.h>
#include <string>

string var1 = "goal", var2 = "boal";
if (strcasecmp(var1.c_str(),var2.c_str()) == 0) {
    cout << "This will NOT print" << endl;
} else {
    cout << "This will print." << endl;
} 

Comparing char pointers:
#include <strings.h>

char* var1 = "goal", var2 = "boal";
if (strcasecmp(var1,var2) == 0) {
    cout << "This will NOT print" << endl;
} else {
    cout << "This will print." << endl;
} 

The comparision of equals 0 is needed because strcasecmp returns an integer, so if the returned integer is equals to zero, the chars / strings are equal. Any different value from zero indicates that the strings are different.
You can find the documentation here: http://man7.org/linux/man-pages/man3/strcasecmp.3.html

Thanks!
Fernando Paladini.

0 comentários: