C++ Programming Write a function that determines if two strings are anagrams. Th
ID: 3797127 • Letter: C
Question
C++ Programming
Write a function that determines if two strings are anagrams. The function should not be case sensitive and should disregard any punctuation or spaces. Two strings are anagrams if the letters can be rearranged to form each other. For example, "Eleven plus two" is an anagram of Twelve plus one". Each string contains one "v", three "e's", two "l's", etc... Test your function with several strings that are anagrams and non-anagrams. You may use either the string class or a C-style string Hint: Count the number of each letter for the two strings and compare the two "histograms". Hint: Use an array of size 26 for the histogram. If two strings entered are "eleven plus two" and "twelve plus one Enter two strings. They are anagrams If two strings entered are "Go Pokes" and "Go Sooners Enter two strings. They are not anagrams.Explanation / Answer
#include <iostream>
#include <string>
#include <cctype>
# define NO_OF_CHARS 26
using namespace std;
void build_histogram(int letters[], string s)
{
for (int i = 0; s[i] ; i++)
{
if (islower(s[i]))
{
letters[s[i] - 'a']++;
}
else
{
if (isupper(s[i]))
{
letters[s[i] - 'A']++;
}
}
}
}
bool anagrams(string s1, string s2)
{
int count1[NO_OF_CHARS] = {0};
int count2[NO_OF_CHARS] = {0};
build_histogram(count1, s1);
build_histogram(count2, s2);
int i;
for (i = 0; i < NO_OF_CHARS; i++)
if (count1[i] != count2[i])
return false;
return true;
}
int main()
{
string s1, s2;
cout << "Enter two strings." << endl;
getline(cin, s1);
getline(cin, s2);
if (anagrams(s1, s2))
{
cout << "They are anagrams!" <<endl;
}
else
{
cout << "They are not anagrams." << endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.