0
0
CppProgramBeginner · 2 min read

C++ Program to Check Anagram with Example

A C++ program to check an anagram sorts both strings using std::sort and compares them with == to return true if they match, false otherwise.
📋

Examples

Input"listen", "silent"
OutputAnagram
Input"hello", "world"
OutputNot an Anagram
Input"triangle", "integral"
OutputAnagram
🧠

How to Think About It

To check if two words are anagrams, think of it like checking if they have the same letters in any order. If you sort both words alphabetically and they become exactly the same, then they are anagrams. Otherwise, they are not.
📐

Algorithm

1
Get two input strings from the user.
2
Remove spaces and convert both strings to lowercase for fair comparison.
3
Sort the characters of both strings alphabetically.
4
Compare the sorted strings.
5
If they are equal, print 'Anagram'; otherwise, print 'Not an Anagram'.
💻

Code

cpp
#include <iostream>
#include <algorithm>
#include <string>
#include <cctype>

bool areAnagrams(std::string s1, std::string s2) {
    s1.erase(std::remove_if(s1.begin(), s1.end(), ::isspace), s1.end());
    s2.erase(std::remove_if(s2.begin(), s2.end(), ::isspace), s2.end());
    std::transform(s1.begin(), s1.end(), s1.begin(), ::tolower);
    std::transform(s2.begin(), s2.end(), s2.begin(), ::tolower);
    std::sort(s1.begin(), s1.end());
    std::sort(s2.begin(), s2.end());
    return s1 == s2;
}

int main() {
    std::string str1, str2;
    std::cout << "Enter first string: ";
    std::getline(std::cin, str1);
    std::cout << "Enter second string: ";
    std::getline(std::cin, str2);

    if (areAnagrams(str1, str2))
        std::cout << "Anagram" << std::endl;
    else
        std::cout << "Not an Anagram" << std::endl;

    return 0;
}
Output
Enter first string: listen Enter second string: silent Anagram
🔍

Dry Run

Let's trace the example input "listen" and "silent" through the code

1

Input strings

str1 = "listen", str2 = "silent"

2

Remove spaces

No spaces to remove, strings remain "listen" and "silent"

3

Convert to lowercase

Both strings already lowercase: "listen", "silent"

4

Sort strings

Sorted str1 = "eilnst", Sorted str2 = "eilnst"

5

Compare sorted strings

"eilnst" == "eilnst" is true

6

Print result

Output: Anagram

Stepstr1str2
Initiallistensilent
After removing spaceslistensilent
After lowercaselistensilent
After sortingeilnsteilnst
💡

Why This Works

Step 1: Normalize strings

Removing spaces and converting to lowercase ensures the comparison ignores case and spaces, making it fair.

Step 2: Sort characters

Sorting rearranges letters so that if two strings have the same letters, their sorted forms will be identical.

Step 3: Compare sorted strings

If sorted strings match exactly, the original strings are anagrams; otherwise, they are not.

🔄

Alternative Approaches

Frequency counting with arrays
cpp
#include <iostream>
#include <string>
#include <cctype>

bool areAnagrams(std::string s1, std::string s2) {
    int count[256] = {0};
    for (char c : s1) {
        if (!isspace(c)) count[tolower(c)]++;
    }
    for (char c : s2) {
        if (!isspace(c)) count[tolower(c)]--;
    }
    for (int i = 0; i < 256; i++) {
        if (count[i] != 0) return false;
    }
    return true;
}

int main() {
    std::string str1, str2;
    std::cout << "Enter first string: ";
    std::getline(std::cin, str1);
    std::cout << "Enter second string: ";
    std::getline(std::cin, str2);

    if (areAnagrams(str1, str2))
        std::cout << "Anagram" << std::endl;
    else
        std::cout << "Not an Anagram" << std::endl;

    return 0;
}
This method counts letter frequencies and compares counts, which can be faster for long strings without sorting.
Using std::unordered_map for frequency
cpp
#include <iostream>
#include <string>
#include <unordered_map>
#include <cctype>

bool areAnagrams(std::string s1, std::string s2) {
    std::unordered_map<char, int> freq;
    for (char c : s1) {
        if (!isspace(c)) freq[tolower(c)]++;
    }
    for (char c : s2) {
        if (!isspace(c)) freq[tolower(c)]--;
    }
    for (auto &p : freq) {
        if (p.second != 0) return false;
    }
    return true;
}

int main() {
    std::string str1, str2;
    std::cout << "Enter first string: ";
    std::getline(std::cin, str1);
    std::cout << "Enter second string: ";
    std::getline(std::cin, str2);

    if (areAnagrams(str1, str2))
        std::cout << "Anagram" << std::endl;
    else
        std::cout << "Not an Anagram" << std::endl;

    return 0;
}
This approach uses a hash map to count characters, useful for Unicode or extended character sets.

Complexity: O(n log n) time, O(n) space

Time Complexity

Sorting both strings takes O(n log n) time, where n is the length of the strings. Comparison is O(n).

Space Complexity

Extra space is used for sorting and storing copies of the strings, which is O(n).

Which Approach is Fastest?

Frequency counting methods run in O(n) time and can be faster than sorting for large inputs, but sorting is simpler to implement.

ApproachTimeSpaceBest For
Sorting and comparingO(n log n)O(n)Simple and short strings
Frequency counting with arrayO(n)O(1)ASCII characters, large strings
Frequency counting with unordered_mapO(n)O(n)Unicode or extended character sets
💡
Always normalize strings by removing spaces and converting to lowercase before checking anagrams.
⚠️
Forgetting to handle case differences or spaces causes false negatives when checking anagrams.