1. Introduction
An anagram is a word or phrase that is formed by rearranging the letters of another word or phrase, using all the original letters exactly once. For instance, "listen" is an anagram of "silent". In this post, we will explore a C++ program that checks whether one string is an anagram of another.
2. Program Overview
The approach we'll be using involves counting the frequency of each character in both strings and then comparing these frequencies. If the frequencies are identical for both strings, then the strings are anagrams of each other.
3. Code Program
#include <iostream>
#include <string>
using namespace std;
bool areAnagrams(string str1, string str2) {
// If lengths are different, they can't be anagrams
if (str1.length() != str2.length()) return false;
int count[256] = {0}; // Assuming ASCII characters
// Increase counts using str1, and decrease using str2
for (int i = 0; i < str1.length(); i++) {
count[str1[i]]++;
count[str2[i]]--;
}
// If the strings are anagrams, all counts will be 0
for (int i = 0; i < 256; i++) {
if (count[i] != 0) return false;
}
return true;
}
int main() {
string str1 = "listen", str2 = "silent";
if (areAnagrams(str1, str2))
cout << str1 << " and " << str2 << " are anagrams.";
else
cout << str1 << " and " << str2 << " are not anagrams.";
return 0;
}
Output:
listen and silent are anagrams.
4. Step By Step Explanation
1. The areAnagrams function first checks if the lengths of the two strings are different. If they are, the strings cannot be anagrams.
2. Then, we utilize an array count of size 256 (assuming an ASCII character set) to keep track of character frequencies. We increment counts for characters in str1 and decrement for characters in str2. If the strings are truly anagrams, then all counts should return to 0 by the end of this process.
3. In the main function, we simply input two strings and call the areAnagrams function to check for their anagram status, then print the result.
Comments
Post a Comment
Leave Comment