Write C++ a function that determines if two strings are anagrams. The function s
ID: 3671622 • Letter: W
Question
Write C++ 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.
Sample output (bolded text denote input from user)
<program start>
Enter two strings.
eleven plus two
twelve plus one
They are anagrams!
<program end>
<program start>
Enter two strings.
Go Pokes
Go Sooners
They are not anagrams.
<program end>
Note: Your program must compile, Make sure that you are submitting your source code not only the excecutible file
Explanation / Answer
#include <iostream>
#include<string>
#include<ctype>
using namespace std;
int main()
{
char s1[20],s2[20];
cout<<"enter two strings"<<endl;
cin>>s1>>s2;
if(anagrams(s1,s2,strlen(s1),.strlen(s2)))
cout<<"given strings are anagrams"<<endl;
else
cout<<"given strings are not anagrams"<<endl;
}
int anagrams(char s1[],char s2[],int len1,int len2)
{
char ch;
int a[26]={0},b[26]={0},i,j,count;
for(i=0;i<len1;i++)
{
ch=s1[i];
ch=toupper(ch);
count=1;
for(j=1;j<len1;j++)
if(ch==s1[j])
count++;
a[toascii(ch)-65]=count;
}
for(i=0;i<len2;i++)
{
ch=s2[i];
ch=toupper(ch);
count=1;
for(j=1;j<len2;j++)
if(ch==s2[j])
count++;
a[toascii(ch)]=count;
}
for(i=0;i<26;i++)
if(a[i]!=b[i])
return 0;
return 1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.