m2skills

anagrams CPP

Jul 13th, 2017
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.62 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <algorithm>
  4. #include <cctype>
  5. using namespace std;
  6.  
  7. // function to check if 2 strings are anagrams or not
  8. void check_anagram(string str1, string str2)
  9. {
  10.     // we create a boolean to denote if the strings are anagrams or not
  11.     bool is_anagram = true;
  12.  
  13.     // making a copy of strings
  14.     string s1 = str1;
  15.     string s2 = str2;
  16.  
  17.     // removing all the white spaces
  18.     str1.erase(remove(str1.begin(), str1.end(), ' '), str1.end());
  19.     str2.erase(remove(str2.begin(), str2.end(), ' '), str2.end());
  20.  
  21.    
  22.  
  23.     // comparing lengths of the strings
  24.     if(str1.size() != str2.size()){
  25.         is_anagram = false;
  26.     }else{
  27.        
  28.         // converting the string to lower
  29.         transform(str1.begin(), str1.end(), str1.begin(),::tolower);
  30.         transform(str2.begin(), str2.end(), str2.begin(),::tolower);
  31.        
  32.         // sorting the string characters and comparing if the resultant strings are the same
  33.         sort(str1.begin(), str1.end());
  34.         sort(str2.begin(), str2.end());
  35.  
  36.         if (!str1.compare(str2)){
  37.             is_anagram = true;
  38.         }else{
  39.             is_anagram = false;
  40.         }
  41.        
  42.     }
  43.    
  44.     // printing the results
  45.     if(is_anagram){
  46.         cout<<s1<<" and "<<s2<<" are Anagrams"<<endl;
  47.     }else{
  48.         cout<<s1<<" and "<<s2<<" are not Anagrams"<<endl;
  49.     }
  50.     return;
  51. }
  52.  
  53. int main(){
  54.     check_anagram("Mother In Law", "Hitler Woman");
  55.  
  56.     check_anagram("DORMITORY", "Dirty Room");
  57.  
  58.     check_anagram("ASTRONOMERS", "NO MORE STARS");
  59.  
  60.     check_anagram("Toss", "Shot");
  61.  
  62.     check_anagram("joy", "enjoy");
  63.  
  64.     check_anagram("HOST", "shot");
  65.  
  66.     check_anagram("repacks", "PaCkErs");
  67.  
  68.     check_anagram("LISTENED", "ENLISTED");
  69.  
  70.     check_anagram("NAMELESS", "salesmen");
  71. }
Add Comment
Please, Sign In to add comment