1

in this code i'm comparing between two strings i did it correctly, but i don't want to consider the letters' case.

for ex: first string: aaaa, second string: aaaA. the output should be 0 or equal.

is there any ideas to fix this?

#include <iostream> #include <algorithm> #include <string> using namespace std; int main() { cout << "enter the first string" << endl; string x; cin >> x; cout << "enter the second string" << endl; string y; cin >> y; cout << endl; sort(x.begin(), x.end()); sort(y.begin(), y.end()); cout << x << endl; cout << y << endl; if (x.compare(y) < 0) { cout << "-1" << endl; } if (x.compare(y) > 0) { cout << "1" << endl; } if (x.compare(y) == 0) { cout << "0" << endl; } } 
5
  • 1
    You could transform both input strings to lowercase prior to comparison; see e.g. How to convert std::string to lower case?. Commented Jun 16, 2020 at 7:30
  • @dfri No, that is a bad solution. It will fail for some international strings. Commented Jun 16, 2020 at 7:31
  • @KonradRudolph Ah I was not aware this was the case for std::basic_string<char>, thanks. Commented Jun 16, 2020 at 7:33
  • 1
    lowercase 2 strings before comparing them. Commented Jun 16, 2020 at 7:33
  • @dfri My concern is unrelated with std::basic_string, it applies to every string type in every programming language. Admittedly C++ strings are even worse since tolower and toupper are broken. Commented Jun 16, 2020 at 7:35

2 Answers 2

1

You can use std::tolower to convert the strings x and y to its lower case representation and than compare the two lowercase strings.

#include <algorithm> ... if (std::tolower(x) == std::tolower(y)) { ... } ... 
Sign up to request clarification or add additional context in comments.

8 Comments

Don’t use tolower or toupper to implement case insensitive compare. This will fail for x = "STRASSE" and y = "straße", which should compare equal.
Why should "STRASSE" and "straße" are equal? "SS" is not equal to "ß".
Because that’s what the rules of German orthography say (DIN 5007-1).
The OP asked for a case insensitive string comparison. What you are mentioning is a semantic comparison.
"straße" is indeed a bad example; yet, there's a locale-specific bug-o-feature with Unicode and Turkish locale where "I" (same char code as Latin) would lowercase to "ı", and "İ", to "i" (again, same as Latin), if your OS locale is Turkish. So tolower("Istanbul") == tolower("istanbul") would be false with Turkish OS locale and true, otherwise.
|
0

Solution from here

if (std::toupper(x) == std::toupper(y)) { cout << "0" << endl; } 

3 Comments

Don’t use tolower or toupper to implement case insensitive compare. This will fail for x = "STRASSE" and y = "straße", which should compare equal.
But this is not part of the initial question.
The question was about strings not about chars.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.