C++ How To Check if Two Strings Are Anagrams
Check if Two Strings Are Anagrams
Two words are anagrams if they have the same letters in a different order, like "listen" and "silent". Sort both words, and compare them:
Example
string word1 = "listen";
string word2 = "silent";
sort(word1.begin(), word1.end());
sort(word2.begin(), word2.end());
if (word1 == word2) {
cout << "The words are anagrams";
} else {
cout << "The words are not anagrams";
}
Explanation:sort() puts the letters of each word in alphabetical order. Both words become "eilnst".
If the sorted words are equal, they have the same letters.