How to find words that contain / consist only of a given char sequence

I want to scroll through a dictionary file and find words containing only the given characters

Dgo example

Desired results: dog, god

NOT words containing (inside) these characters

I am working with the following code:

            while((dictionaryWord = br_.readLine()) != null) 
            {   

                    if(dictionaryWord.contains(getWord()))
                        System.out.println(dictionaryWord);

            }

But it gives me all the words that contain the given characters - NOT DESIRED

+3
source share
2 answers

Without regular expressions:

public static boolean sameCharacters(String left, String right) {
    return sortCharacters(left).equals(sortCharacters(right));
}

private static String sortCharacters(String s) {
    final char[] chars = s.toCharArray();
    Arrays.sort(chars);
    return String.valueOf(chars);
}

UPDATE : more efficient version (thanks to user384706):

public static boolean sameCharacters(String left, String right) {
    return Arrays.equals(sortCharacters(left), sortCharacters(right));
}

private static char[] sortCharacters(String s) {
    final char[] chars = s.toCharArray();
    Arrays.sort(chars);
    return chars;
}
+4
source

You can check by doing

if (word.matches("[dgo]*")) {
    ...
}
+2
source

All Articles