Home > front end >  How to ignore text case while comparing two strings in C ?
How to ignore text case while comparing two strings in C ?

Time:04-27

I am a beginner coder. I am trying to create a program which will compare two strings alphabetically. But It will ignore the text case. I am facing problem on it. How can I ignore the text case in C ?

#include <iostream>

using namespace std;

int main() {

    string a, b;

    cin >> a;
    cin >> b;

    if ( a > b) {
        cout << "1";
    }
    else if ( a < b) {
        cout << "-1";
    }
    else if (a == b) {
        cout << "0";
    }

}

CodePudding user response:

You can convert both strings to lower case before the comparison via std::tolower:

for (auto& c : a) c = std::tolower(static_cast<unsigned char>(c));
for (auto& c : b) c = std::tolower(static_cast<unsigned char>(c));

CodePudding user response:

Use a case-insensitive comparison function, such as C's strcmpi(), or Windows's CompareStringA() with the NORM_IGNORECASE flag, or Posix's strcasecmp(), etc

CodePudding user response:

I would recommend using a loop and converting both strings to lowercase or lowercase by using std::toupper or std::tolower

for(const auto& i:a)x=std::tolower(x);
for(const auto& i:a)x=std::tolower(x);
  • Related