Jahin Ahnaf
Jahin Ahnaf

Reputation: 17

How to ignore text case while comparing two strings in C++?

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";
    }

}

Upvotes: 0

Views: 222

Answers (3)

Remy Lebeau
Remy Lebeau

Reputation: 597051

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

Upvotes: 0

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122830

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));

Upvotes: 3

RD-43337
RD-43337

Reputation: 1

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);

Upvotes: -2

Related Questions