Check if two strings are anagrams or not in c++
Reading time : Less than 20 minutes
Another programming puzzle on these days is to check whether two strings are anagrams or not. As per the definition from Wikipedia, anagrams are strings with
- Same number of characters apart from white spaces
- The letters will be scrambled across the string
- Intersection of both character set will be equal to the set itself
Err… for better English you can read something like this. Anyway, I think you got the overall idea, that is the strings William Shakespeare and I am a weakish speller are anagrams. Now, lets figure out how can we hack the problem. Lets start writing a Phrase class.
class Phrase {
char* string;
public:
Phrase( char* initialString ) {
string = ( char* )malloc( strlen( initialString ) );
string = initialString;
}
int numChars() {
unsigned int count = 0;
for(unsigned int i = 0; i < strlen( string ); i++ )
if( string[i] != ’ ’ )
count++;
return count;
}
void removeSpace() {
char* output = ( char* )malloc( numChars() + 1 );
unsigned int j = 0;
for( unsigned int i = 0; string[i] != ‘\0’; i++ )
if( string[i] != ’ ’ )
output[j++] = string[i];
output[j] = ‘\0’;
string = output;
}
void uptoLow() {
for( unsigned int i = 0; i < strlen( string ); i++ )
string[i] = tolower(string[i]);
}
void sortString() {
for(unsigned int i = 0; i < strlen( string ); i++ )
for(unsigned int j = 0; j < strlen( string ) - 1; j++ )
if( string[j] > string[j+1] ) {
char temp = string[j];
string[j] = string[j+1];
string[j+1] = temp;
}
}
bool isEqual( Phrase comPhrase ) {
return !strcmp( this->string, comPhrase.string );
}
bool isAnagram( Phrase comPhrase ) {
this->removeSpace();
this->uptoLow();
this->sortString();
comPhrase.removeSpace();
comPhrase.uptoLow();
comPhrase.sortString();
return this->isEqual( comPhrase );
}
};
Pretty clear huh? This class has all of the functionality to handle two strings and check if they are anagrams or not. Now we can, create the main function.
int main( int argc, char* argv[] ) {
Phrase one(“Madonna Louise Ciccone”);
Phrase two(“Occasional nude income”);
one.isAnagram( two ) ? cout«”Yes, they are anagrams!” : cout«”No, they are not!”;
return 0;
}
Now, compile the code and run it. By the way, you are expected to get an output like,
Yes, they are anagrams!
//See you in the afterlife
//Subin Sebastian





