anagram checker wont work ...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jcollins1991
    New Member
    • Nov 2007
    • 1

    #1

    anagram checker wont work ...

    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).


    [CODE=java]while (str2.get_Lengt h() != 0) //<---- checks whether second string is "cleared"
    {

    //loop, from start of string (k = 0) to end of string (length2) for (k = 0; k <= length2; k = k + 1)
    {
    char1 = str1.charAt(0);
    y = 0; resets y
    char2 = str2.charAt(0);
    if (char2 == char1) //checks if two are the same, if they are, makes y = point in string with char 2
    {
    y = str2.IndexOf(ch ar2);
    }

    if (y > -1) //checks if y is positive, if so, takes a substring of all other letters
    str2 = (str2.substring (0, y)) + (str2.substring (y + 1));
    }


    } [/CODE]

    can anyone figure out why it wont work???
    Last edited by Ganon11; Nov 3 '07, 08:21 PM. Reason: Please use the [CODE] tags provided.
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    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.

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      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

      Comment

      Working...