Anagram

Anagram in C++

To create an anagram in C++, you can follow these steps:

  1. Get the input strings: Prompt the user to enter two strings that you want to check for anagram properties. You can use the std::cin function to get user input.

  2. Check the lengths of the strings: Compare the lengths of the two strings. If they are not equal, the strings cannot be anagrams. You can use the length() function to get the length of a string.

  3. Create character frequency maps: Create two maps to store the frequency of each character in the strings. You can use the std::map container to create the maps. Iterate over each character in the first string and increment its frequency in the first map. Similarly, iterate over each character in the second string and increment its frequency in the second map.

  4. Compare the character frequency maps: Compare the two maps created in the previous step. If the maps are equal, the strings are anagrams. You can use the == operator to compare the maps.

Here's an example implementation of the above steps:

#include <iostream>
#include <map>

bool isAnagram(const std::string& str1, const std::string& str2) {
    // Step 2: Check the lengths of the strings
    if (str1.length() != str2.length()) {
        return false;
    }

    // Step 3: Create character frequency maps
    std::map<char, int> freqMap1, freqMap2;
    for (char c : str1) {
        freqMap1[c]++;
    }
    for (char c : str2) {
        freqMap2[c]++;
    }

    // Step 4: Compare the character frequency maps
    return freqMap1 == freqMap2;
}

int main() {
    // Step 1: Get the input strings
    std::string str1, str2;
    std::cout << "Enter the first string: ";
    std::cin >> str1;
    std::cout << "Enter the second string: ";
    std::cin >> str2;

    // Check if the strings are anagrams
    if (isAnagram(str1, str2)) {
        std::cout << "The strings are anagrams." << std::endl;
    } else {
        std::cout << "The strings are not anagrams." << std::endl;
    }

    return 0;
}

This implementation uses a map to store the frequency of each character in the strings. By comparing the maps, we can determine if the strings are anagrams or not.

Please note that this implementation assumes case-sensitive anagrams and considers all characters in the strings, including spaces and punctuation. If you want to ignore case or certain characters, you can modify the implementation accordingly.

I hope this helps! Let me know if you have any further questions.