Anagram Check Program in C++
Introduction
This program demonstrates how to check if two strings are anagrams of each other in C++. Two strings are considered anagrams if they contain the same characters with the same frequency, but possibly in a different order.
C++ Program
#include <iostream>
#include <algorithm>
#include <string>
/**
* Function to check if two strings are anagrams of each other.
*
* @param str1 The first string.
* @param str2 The second string.
* @return true if the strings are anagrams, false otherwise.
*/
bool areAnagrams(const std::string &str1, const std::string &str2) {
// If lengths are not equal, the strings cannot be anagrams
if (str1.length() != str2.length()) {
return false;
}
// Create copies of the strings and sort them
std::string sortedStr1 = str1;
std::string sortedStr2 = str2;
std::sort(sortedStr1.begin(), sortedStr1.end());
std::sort(sortedStr2.begin(), sortedStr2.end());
// Compare the sorted strings
return sortedStr1 == sortedStr2;
}
/**
* Main function to test the anagram checking function.
*
* @return int Exit status of the program.
*/
int main() {
// Example strings
std::string str1 = "listen";
std::string str2 = "silent";
// Check if the strings are anagrams
if (areAnagrams(str1, str2)) {
std::cout << str1 << " and " << str2 << " are anagrams." << std::endl;
} else {
std::cout << str1 << " and " << str2 << " are not anagrams." << std::endl;
}
return 0;
}
Explanation
The program consists of a function areAnagrams
and a main
function:
areAnagrams
: This function takes two strings as input and returns a boolean value indicating whether they are anagrams. It first checks if the lengths of the strings are equal. If not, it immediately returnsfalse
. If the lengths are equal, it sorts both strings and compares the sorted versions. If the sorted strings are identical, the original strings are anagrams.main
: This is the entry point of the program. It defines two example strings, calls theareAnagrams
function to check if they are anagrams, and prints the result.
Key Points:
- The program uses the
std::sort
function from the C++ Standard Library to sort the strings. - Sorting the strings and then comparing them is a straightforward way to check for anagrams.
- If the strings have different lengths, they cannot be anagrams, and the function returns
false
immediately.