Anagram Checker: Compare Strings using Sorting and Normalization

Anagram Checker: Compare Strings using Sorting and Normalization

In this C++ exercise, you will develop a program that determines if two strings are anagrams of each other. An anagram is formed by rearranging the letters of one word to produce another, using all original letters exactly once (e.g., "listen" and "silent").

This task is perfect for practicing string manipulation, sorting techniques, and logical comparison in C++.

Core Concepts

Case Normalization

Using transform with ::tolower ensures that "Listen" and "silent" are correctly identified as anagrams regardless of casing.

Sort & Compare

By sorting both strings alphabetically, two anagrams will result in identical character sequences, making comparison trivial.

Objectives

  • 1. Prompt the user to input two separate strings.
  • 2. Standardize the strings by converting all characters to lowercase.
  • 3. Sort both strings alphabetically using the <algorithm> library.
  • 4. Compare the results and display a clear confirmation message.

Example C++ Code

anagram_checker.cpp Source Code
#include <iostream>
#include <algorithm> // Needed for sort and transform
#include <string>

using namespace std;

// Boolean function to handle the logic
bool areAnagrams(string str1, string str2) {
    // 1. Normalize both strings to lowercase
    transform(str1.begin(), str1.end(), str1.begin(), ::tolower);
    transform(str2.begin(), str2.end(), str2.begin(), ::tolower);

    // 2. Sort characters alphabetically
    sort(str1.begin(), str1.end());
    sort(str2.begin(), str2.end());

    // 3. Comparison
    return str1 == str2;
}

int main() {
    string word1, word2;

    cout << "Enter the first word: ";
    cin >> word1;

    cout << "Enter the second word: ";
    cin >> word2;

    if (areAnagrams(word1, word2)) {
        cout << "The words are anagrams." << endl;
    } else {
        cout << "The words are not anagrams." << endl;
    }

    return 0;
}

Console Output:

Enter the first word: listen
Enter the second word: silent
The words are anagrams.
Keywords & Concepts
String Sorting STL Algorithms String Transformation Anagram Logic
© C++ Programming Exercises. Master the art of performance coding.