Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <algorithm>
- #include <cctype>
- using namespace std;
- // function to check if 2 strings are anagrams or not
- void check_anagram(string str1, string str2)
- {
- // we create a boolean to denote if the strings are anagrams or not
- bool is_anagram = true;
- // making a copy of strings
- string s1 = str1;
- string s2 = str2;
- // removing all the white spaces
- str1.erase(remove(str1.begin(), str1.end(), ' '), str1.end());
- str2.erase(remove(str2.begin(), str2.end(), ' '), str2.end());
- // comparing lengths of the strings
- if(str1.size() != str2.size()){
- is_anagram = false;
- }else{
- // converting the string to lower
- transform(str1.begin(), str1.end(), str1.begin(),::tolower);
- transform(str2.begin(), str2.end(), str2.begin(),::tolower);
- // sorting the string characters and comparing if the resultant strings are the same
- sort(str1.begin(), str1.end());
- sort(str2.begin(), str2.end());
- if (!str1.compare(str2)){
- is_anagram = true;
- }else{
- is_anagram = false;
- }
- }
- // printing the results
- if(is_anagram){
- cout<<s1<<" and "<<s2<<" are Anagrams"<<endl;
- }else{
- cout<<s1<<" and "<<s2<<" are not Anagrams"<<endl;
- }
- return;
- }
- int main(){
- check_anagram("Mother In Law", "Hitler Woman");
- check_anagram("DORMITORY", "Dirty Room");
- check_anagram("ASTRONOMERS", "NO MORE STARS");
- check_anagram("Toss", "Shot");
- check_anagram("joy", "enjoy");
- check_anagram("HOST", "shot");
- check_anagram("repacks", "PaCkErs");
- check_anagram("LISTENED", "ENLISTED");
- check_anagram("NAMELESS", "salesmen");
- }
Add Comment
Please, Sign In to add comment