Check for anagrams. - C++ STL

C++ examples for STL:string

Description

Check for anagrams.

Demo Code

#include <iostream>
#include <cctype>
#include <string>

using std::string;

int main() {/*from w w w . j a  v a  2s .  c  om*/
  string word1 {"level"};
  string word2 {"level"};

  if (word1.length() != word2.length()) {
    std::cout << word1 << " and " << word2 << " are different lengths so they can't be anagrams!" << std::endl;
    return 0;
  }

  string word2_copy {word2};                                // Copy word2 - because we will delete characters
  for (int i {}; i < word1.length(); ++i){
    // Loop over all the characters in word2
    for (int j {}; j < word2_copy.length(); j++)
      if (std::tolower(word2_copy[j]) == std::tolower(word1[i])) {
        word2_copy.erase(j, 1);   // Character found so erase from word2
        break;
      }
  }

  std::cout << word1 << " and " << word2 << " are "
    << (word2_copy.length() ? "not" : "")
    << " anagrams of one another."
    << std::endl;
}

Result


Related Tutorials