Monday, May 24, 2010

How to check for anagrams in C++?

I need a program to check two entered strings of text and see if the strings entered are anagrams, disregarding the case of the letters, and ignoring spaces (i.e. "Mother in Law" and "Woman Hitler" are anagrams). The strings won't be any longer than 500 characters.





I can't figure out what to do with this because it has to use arrays, which I have never been good with, and the emphasis is supposed to be on use of c strings.





I do know that it essentially needs to do this: change the case of the two strings and remove anything that isn't a letter, then sort the letters, and finally determine if they are the same (are they anagrams?).





I'm trying to keep this "simple." Can anyone help me with a program that does this? Thanks SO MUCH in advance!

How to check for anagrams in C++?
Well, in programming, we always try to get a clear problem definition and logical solution before we start coding.





Oh wait...I was thinking of a palindrome...





Answering questions for people is like programming. We should think 1st. :-)





Yes, sorting is a good idea. And so is changing case....changing case before the sort will enable a clean sort...





1 - Change both strings to lowercase with _strlwr( char *string );





2 - sort both strings... see qsort() for a cheap easy solution that your compiler probably already has. All mine have had qsort().





3 - kill whitespace. You mite need to build a function for this...but qsort should have moved all the whitespace to the end (or begining) which makes it easier (especially if at end).


- You can kill trailing whitespace very easily by putting a null '\0' at the very first instance of white space, if whitespace is at the end, like so:


for(ii=0; ii%26lt; strlen(string); ii++)


if(string[ii] == ' ') // a space?


{


string[ii] = '\0'; ///kill it and cap the string


break; // we're done


}








4 - compare the two strings with strcmp(). If they match, they're anagrams





That's our flow plan and function ID.
Reply:so its a "string compare" your doing ? ;-)





on the first one, u could have a pointer.. basically u check a letter against the second string...





you either have true / false... you need a recurssive loop that checks till end of line / null





it will either return TRUE and exit that loop.. then get ++ the string1 .. and repeat scanning string2..





if it returns false, after the end of string2... obviously they aren't the same..





i would have an array or struct, with a flag in for each character.. 1 exists.. 0 doesn't exsist





then print results.. eg..





found =


not same letters =





and no i'm not gonna do the code, u've had enough clues to do ya own homework =)
Reply:It is not that easy. May be you can contact a C++ expert at websites like http://askexpert.info/


No comments:

Post a Comment