Check if two strings S1 and S2 are anagram.

Hi,
I'm trying to solve few problems related to strings, In most of the cases, I know how to go about it(algorithm), but I don't know how to implement it using "strings".
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//This program finds out, if given two strings are anagram or no?

#include <iostream>
#include <stdlib.h>
using namespace std;

bool Anagram(string a,string B)
{
    int LenA = a.size();
    int LenB = b.size();
    if(LenA != LenB)
    return 0;
    string::iterator iA;
    string::iterator iB;
// Now there are two ways to accomplish this:
// 1. Arrange each string in alphabetical order and just compare them. 
// NOTE: Here compare is easy, a.compare(B); but how to arrange them in alphabetical order ? (Character repetition allowed)
// 2. Count each character in each string, and compare if the count of each characters in a matches with count of each characters in b .
    return 0;

}
int main()
{
    string s1,s2;
    cout << "Enter string S1" << endl;
    cin >> s1;
    cout << "Enter string S2" << endl;
    cin >> s2;
    if(Anagram(s1,s2))
    {
        cout << "String :" << s1 << " and String : " << s2 << " are anagram.\n";
    }
    else
    {
        cout << "String :" << s1 << " and String : " << s2 << " are NOT anagram.\n";
    }
    return 0;
}

I've gone through the cplusplus link for string. But I'm not yet able to organize it to solve problem. Want to see some working example, or concepts on, how to implement the two approach I have described in above code snippet. Please help.
Just use standard algorithm (or implement your own sort, in matching signature with std::sort), here is a small and complete example.
1
2
3
4
5
6
7
8
9
10
#include<iostream>
#include<string>
#include<algorithm>
int main()
{
    std::string a("abdc"),b("bacd");
    std::sort(a.begin(),a.end());
    std::sort(b.begin(),b.end());
    std::cout<<"They are "<<((a==b)?"":"not")<<" anagrams.";
}


Of course, put that inside a function, check for size difference first..(which you've already done in the OP) etc.
Last edited on
> 1. Arrange each string in alphabetical order and just compare them.

1. Arrange each string in alphabetical order after removing spaces and punctuation, and just compare them ignoring case.

1
2
3
4
5
6
7
8
9
10
11
12
std::string make_key( std::string str )
{
    static const auto space_or_punct = []( char c ) 
                                       { return std::ispunct(c) || std::isspace(c) ; } ;
    str.erase( std::remove_if( str.begin(), str.end(), space_or_punct ), str.end() ) ;
    for( char& c : str ) c = std::tolower(c) ;
    std::sort( str.begin(), str.end() ) ;
    return str ;
}

bool anagrams( const std::string& a, const std::string& b )
{ return make_key(a) == make_key(b) ; }

Topic archived. No new replies allowed.