My approach for checking anagrams is:
step 1: Remove all the space from both input strings.
step 2: Sort both of the strings.
step 3: Return false if the lengths differ.
step 4 : Return true if all char matches.
#include<iostream>
#include<set>
#include<string>
#include <algorithm>
bool anagrams(std::string usr1,std::string usr2)
{
if(usr1.length()==usr2.length())
{
for(std::string::size_type pos = 0 ; pos<= usr1.length()-1 ; ++pos)
{
if(pos==usr1.size()-1)
{
if(usr1[pos]==usr2[pos])
return true;
}
if(usr1[pos]==usr2[pos])
{
continue ;
}
}
}
return false;
}
int main()
{
std::string userInput1;
std::string userInput2;
std::getline(std::cin,userInput1);
std::getline(std::cin,userInput2);
std::string::iterator end_pos1 = std::remove(userInput1.begin(),userInput1.end(),' ');
userInput2.erase(end_pos1,userInput1.end());
std::string::iterator end_pos2 = std::remove(userInput2.begin(),userInput2.end(),' ');
userInput1.erase(end_pos2,userInput2.end());
std::sort(userInput1.begin(),userInput1.end());
std::sort(userInput2.begin(),userInput2.end());
if(userInput1.empty() || userInput2.empty())
return 0;
if(anagrams(userInput1,userInput2))
std::cout<<"String is anagrams"<<"\n";
else
std::cout<<"String not anagrams"<<"\n";
return 0;
}
anagrams()
doesn't work. It says two strings are equal the first string's last character matches the second string's last character. That is, it reports two strings as anagrams if the highest-value letter of them is the same. \$\endgroup\$