How to Check if Two Strings are Anagrams in C++ | Anagram Checker Function Explained

Spread the love

Understanding the Anagram Checker Program in C++
Basically, an anagram is a word or phrase that forms another word by rearranging its letters and uses all of them exactly once. This C++ program will illustrate a simple and efficient method of determining whether two given strings are anagrams.

Code:

Following is a detailed explanation of the code for your understanding of the program.

  1. Header files

#include<iostream>: This library is used for input and output operations like cin and cout.
#include<string>: For string handling.

2. Anagram Function


The function takes two strings (str1 and str2) as input.
It returns a boolean value: true if they are anagrams, false otherwise.

2. Checking length of the string

If the lengths of the strings are different, they cannot be anagrams.
It prints “Not an Anagram” and returns early.

3. Array for counting the frequnecy

Create an array to count the frequency of each character in the strings.
Why 26? This assumes the strings contain lowercase English letters only (a to z).

4. Increase the frequency for str1


Each character in str1 increments the corresponding index in the count array.

5. Decrease the frequency for str2

Every character in str2 decrements the corresponding index in the count array.
If any character in str2 is not present in str1, frequency will be 0; hence, the strings are not anagrams.

6. output

If all checks pass, the strings are confirmed as anagrams.

7. Main function


Inputs: Two predefined strings (“anagram” and “nagaram”).
Calling the Function: The function anagram determines whether the two strings are anagrams and prints out a message showing its result.

How the Program Works


The function first checks whether the two strings are of the same length. If not, they cannot be anagrams.
It calculates the frequency of each character in the first string using the count array.
It then checks the characters in the second string, reducing their corresponding counts. If any character count goes negative or is zero when it shouldn’t be, the strings are not anagrams.
If all characters balance out, the strings are anagrams.


Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top