By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,573 Members | 3,017 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,573 IT Pros & Developers. It's quick & easy.

anagram checker wont work ...

P: 1
im trying to make a program thats supposed to check whether 2 strings are anagrams of each other (anagram = same letters in both strings, but in different orders... "cool as wet art" , and "cs at waterloo" for example).


Expand|Select|Wrap|Line Numbers
  1. while (str2.get_Length() != 0)   //<---- checks whether second string is "cleared"
  2.         {
  3.  
  4.                        //loop, from start of string (k = 0) to end of string (length2)                      for (k = 0; k <= length2; k = k + 1)
  5.             {
  6.                 char1 = str1.charAt(0); 
  7.                 y = 0;   resets y
  8.                 char2 = str2.charAt(0);  
  9.                 if (char2 == char1) //checks if two are the same, if they are, makes y = point in string with char 2
  10.                                 {
  11.                         y = str2.IndexOf(char2);
  12.                                 }            
  13.  
  14.                                  if (y > -1) //checks if y is positive, if so, takes a substring of all other letters
  15.                         str2 = (str2.substring(0, y)) + (str2.substring(y + 1));
  16.             }
  17.  
  18.  
  19.         }  
can anyone figure out why it wont work???
Nov 3 '07 #1
Share this Question
Share on Google+
2 Replies


Ganon11
Expert 2.5K+
P: 3,652
Well, two things:

1) If char1 and char2 are the same character, then the IndexOf function will always return 0, because that character is the first character. If they aren't equal, you don't do anything to get the index of that character.

2) You don't have anything returning false if the two Strings are not anagrams of each other.
Nov 3 '07 #2

Expert 10K+
P: 11,448
Sort both strings and check whether or not both sorted strings are equal, e.g. both
strings "baa" and "aba" sorted are equal to "aab".

kind regards,

Jos
Nov 3 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.