0

I have to create a Java program that returns true if two strings are composed by the same letters like "EMS" and "MES", or false if it is not the case.

I tried to develop some code and I finally found a solution but It only works for words which have all letters different (no letters duplicated) It doesn't work for "EEM" and "EMS".

String mot = "EMS", word="EES";
char[] tab= mot.toCharArray();
char[] vect= word.toCharArray();
int i = mot.length(), j = word.length(), a = 0;      
if (i != j)
    System.out.println("false");
else {
    for (int k=0; k<i; k++) {
        for (int l=0; l<i; l++) {
            if (tab[k] == vect[l])
                a++; 
        }
    }
    if (a == i)
         System.out.println("true");
    else
         System.out.println("false");
}
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Ameni
  • 5
  • 2
  • it's so easy to google it http://stackoverflow.com/questions/3985328/checking-if-2-strings-contain-the-same-characters – StackExploded Feb 12 '15 at 00:10
  • 1
    Sort the two `String`s are then do a simple comparison (even convert them back to `String`s and use `equals`)... – MadProgrammer Feb 12 '15 at 00:14
  • 2
    Uhm, well, `EEM` and `EMS` do not have the same letters indeed; so the output is pretty much expected, right? – fge Feb 12 '15 at 00:15
  • @fge: When he said it doesn't work, I believe he meant the code incorrectly returns `true` for those two strings. – Alan Moore Feb 12 '15 at 09:59
  • Hello, yes i meant it returns true for those two strings I posted the case where this code doesn't work. – Ameni Feb 12 '15 at 22:10

3 Answers3

0

Possible idea to use indexOf() to locate matching chars in each string...

public static boolean sameChars(String str1, String str2){

    for(int i = 0; i < str1.length(); i++){
        if(str2.indexOf(str1.charAt(i)) == -1)
            return false;
    }
    for(int i = 0; i < str2.length(); i++){
        if(str1.indexOf(str2.charAt(i)) == -1)
            return false;
    }
    return true;

}
shirrine
  • 403
  • 3
  • 6
0

How about

new HashSet<Character>(Arrays.asList("EMS".toCharArray())
  .equals(new HashSet<Character>(Arrays.asList("MES".toCharArray()));
Lev Kuznetsov
  • 3,520
  • 5
  • 20
  • 33
  • This does not properly take the case of duplicate letters into account (which was specifically pointed out as a flaw of the original implementation) – Marco13 Feb 12 '15 at 10:35
0

The reason for the false positive result is that you're comparing the E in EMS to both of the Es in EES. You need to get rid of that inner for loop. You also need to sort the arrays before you compare them, as one of the commenters suggested.

I won't provide code to demonstrate because it's such basic-level stuff. If this isn't a homework problem, it should be. :D

Community
  • 1
  • 1
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
  • Thank you for your response, but I wanted to add that I'am new to java so I'am doing my best to get the basics – Ameni Feb 12 '15 at 22:12