-2
bool isAnagram(string s1, string s2){
   if(s1.length() != s2.length())
      return false;

  for(int i =0; i <s1.length();i++){
      int pos = (s2.find(s1[i]);
                 if(pos<0)
                 return false;
                 s2.erase(pos,1);

               }
                 return true;

                 return false;

               }

I write the code about checking Anagram but ignore the requirement of ignoring difference between upper and lower. I have no idea about that. Can you help me? Thanks!

Saveen
  • 4,120
  • 14
  • 38
  • 41
LEO
  • 3
  • 2
  • Initially I was going to mark this as a duplicate of https://stackoverflow.com/questions/11635/case-insensitive-string-comparison-in-c but those answers are so old it's not funny. Regardless, I downvoted because this is so simple to look up you'd have literally spent less time googling "c++ ignore case" – Tas Mar 16 '18 at 05:54

4 Answers4

1

Convert both to lowercase before comparing

std::transform(s1.begin(), s1.end(), s1.begin(), ::tolower);
std::transform(s2.begin(), s2.end(), s2.begin(), ::tolower);
MO1988
  • 57
  • 6
0

The easy way is set both string to lower case(or upper case), and then sort both of them. If s1 and s2 is anagram to each other, then the result should be same.

bigeast
  • 627
  • 5
  • 14
0

you can use algorithm library to convert uppercase to lowercase. before looping add below line to convert it to lower case.

#include <algorithm>
#include <string>
std::transform(s1.begin(), s1.end(), s1.begin(), ::tolower);
std::transform(s2.begin(), s2.end(), s2.begin(), ::tolower);
Roushan
  • 4,074
  • 3
  • 21
  • 38
0

You can simply use the power of the STL algorithm:

#include <iostream>
#include <algorithm>

using namespace std;

bool isSameChar(int a, int b)
{
    return tolower(a) == tolower(b);
}

bool isAnagram(const string& a, const string& b)
{
    return a.size() == b.size()
        && is_permutation(a.begin(), a.end(), b.begin(), isSameChar);
}

int main()
{
    cout << isAnagram("AbcDE", "ebCda") << endl; // true
    cout << isAnagram("AbcDE", "ebCdaa") << endl; // false
    cout << isAnagram("AbcDE", "ebCde") << endl; // false

    return 0;
}
vmario
  • 411
  • 3
  • 15