How do I check for any received type (uppercase or lowercase)?

3

How can I ignore the case for comparison with the default word?

Ex: stack (default word to compare)

Words that could be received: "sTAck" "STACk"

    
asked by anonymous 15.01.2017 / 03:21

3 answers

3

Simple: Convert the text to uppercase and compare. C ++ code example:

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

bool compare(string s1, string s2)
{
    transform(s1.begin(), s1.end(), s1.begin(), ::toupper);
    transform(s2.begin(), s2.end(), s2.begin(), ::toupper);
    return s1 == s2;
}

int main() {

    string s[] = {"sTAck", "STACk", "STAcK", "SSTTAACCKK", "stack", "Extack"};

    for(int i = 0; i < 6; i++)
        cout << s[i] << (compare(s[i], "stack") ? " OK" : " NOK") << endl;

    return 0;
}

Result:

sTAck OK
STACk OK
STAcK OK
SSTTAACCKK NOK
stack OK
Extack NOK

See running on Ideone .

    
15.01.2017 / 03:40
2

I do not know much about C ++, but if you do not need to keep formatting the way it was typed I could use a method to turn letters into uppercase if I'm not mistaken C ++ uses the toupper (var) method to return a string in uppercase (if I'm not mistaken).

I'm more familiar with python, so I use the following:

a = "olamundo".upper() #para maiúsculas

or:

a = "OLAMUNDO".lower() #para minúsculas

I hope I have helped.

ps: You could store the value of the method in another variable and use the initial variable to keep the formatting.

for reference: link

    
15.01.2017 / 03:37
1

There is no native case-insensitive string comparison function in C ++. In Windows you could use "stricmp" and in Linux "strcasecmp".
In pure C ++ it takes a little extra code.

Below, a way of how this comparison could be made in pure C ++, using the generic algorithm "mismatch" and the "toupper" function.

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

const string compare(const string& s1, string const& s2)
{
   if (s1.size() != s2.size()) return "diferentes";

   auto result = mismatch(s1.begin(), s1.end(), s2.begin(), s2.end(),
      [](char c1, char c2) { return ::toupper(c1) == ::toupper(c2); });

   return result.first == s1.end() ? "iguais" : "diferentes";
}

int main()
{
   vector<string> s { "sTAck", "STACk", "STAcK", "SSTTAACCKK", "stack", "xxx" };

   for (const auto& str : s)
       cout << str << ": " << compare(str, "stack") << endl;

   return 0;
}
    
15.01.2017 / 16:12