Check if Two Strings Are Anagrams in C++

In this C++ exercise, you will develop a program that checks whether two given strings are anagrams of each other. An anagram is formed by rearranging the letters of one word to produce another word, using all original letters exactly once. For example, "listen" and "silent" are anagrams.

This task will help you practice string manipulation, sorting techniques, and logical comparison. You'll learn how to normalize input by converting all characters to lowercase and removing spaces if necessary. The core idea is to sort both strings and then compare them—if they match, they are anagrams.

The program should take two strings as input from the user, sort them, and then check if they are equal. This type of exercise is common in interviews and competitive programming, making it excellent for skill-building.

Group

Advanced Conditional Structures in C++

Objective

1. Prompt the user to input two strings.
2. Convert both strings to lowercase to ensure case-insensitive comparison.
3. Sort the characters in both strings alphabetically.
4. Compare the sorted strings.
5. Display whether the two strings are anagrams or not.

Create a program that determines if a given pair of strings are anagrams.

Example C++ Exercise

 Copy C++ Code
#include <iostream>     // Include input/output stream library
#include <algorithm>    // Include algorithm library for sort and transform
#include <string>       // Include string library

using namespace std;

bool areAnagrams(string str1, string str2) {
    // Convert both strings to lowercase
    transform(str1.begin(), str1.end(), str1.begin(), ::tolower);
    transform(str2.begin(), str2.end(), str2.begin(), ::tolower);

    // Sort both strings
    sort(str1.begin(), str1.end());
    sort(str2.begin(), str2.end());

    // Compare sorted strings
    return str1 == str2;
}

int main() {
    string word1, word2; // Variables to store user input

    // Prompt the user for the first word
    cout << "Enter the first word: ";
    cin >> word1;

    // Prompt the user for the second word
    cout << "Enter the second word: ";
    cin >> word2;

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

    return 0; // End of program
}

 Output

Enter the first word: listen
Enter the second word: silent
The words are anagrams.

Share this C++ Exercise


More C++ Programming Exercises of Advanced Conditional Structures in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.