C++ Program to Check if Two Strings are Anagrams
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once. For example, “listen” is an anagram of “silent”. This program will check if two given strings are anagrams of each other.
Program Explanation
The program follows these steps:
- Check if the lengths of the two strings are equal. If not, they cannot be anagrams.
- Create frequency arrays for each string to count the occurrence of each character.
- Compare the frequency arrays. If they are identical, the strings are anagrams.
C++ Program Code
#include <iostream>
#include <algorithm>>
#include <string>>
using namespace std;
// Function to check if two strings are anagrams
bool areAnagrams(string str1, string str2) {
// If lengths are different, they cannot be anagrams
if (str1.length() != str2.length()) {
return false;
}
// Sort both strings
sort(str1.begin(), str1.end());
sort(str2.begin(), str2.end());
// Compare sorted strings
return (str1 == str2);
}
int main() {
string str1, str2;
// Input strings
cout << "Enter the first string: ";
getline(cin, str1);
cout << "Enter the second string: ";
getline(cin, str2);
// Check and output result
if (areAnagrams(str1, str2)) {
cout << "The strings are anagrams." << endl;
} else {
cout << "The strings are not anagrams." << endl;
}
return 0;
}
Explanation
- Program Structure:
- Includes necessary headers:
<iostream>
,<algorithm>
, and<string>
. - Function
areAnagrams
:- Checks if the lengths of the strings are the same.
- Sorts both strings.
- Compares the sorted strings and returns a boolean result.
- Main function:
- Takes user input for two strings.
- Calls
areAnagrams
and prints the result.
- Includes necessary headers:
Documentation
Function: areAnagrams
- Parameters: Two strings (
str1
andstr2
) to be compared. - Returns: A boolean value –
true
if the strings are anagrams,false
otherwise. - Details: This function first checks if the lengths of the two strings are the same. If not, it returns
false
. Then, it sorts both strings and compares them. If the sorted strings are identical, it returnstrue
, indicating the strings are anagrams.
Main Function:
- Prompts the user to input two strings.
- Calls the
areAnagrams
function with the provided strings. - Prints whether the strings are anagrams based on the result from the
areAnagrams
function.