How do I find words that only contain/consist of a

2020-07-20 04:52发布

I wish to loop through a dictionary file and find words that contain only the given characters

Example dgo

Desired results: dog, god

NOT words that contain (within them) the given characters

I am working with the following code:

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

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

            }

But this gives me all words which contain the given characters -- NOT DESIRED

标签: java anagram
2条回答
爷、活的狠高调
2楼-- · 2020-07-20 04:59

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: better performing 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;
}
查看更多
▲ chillily
3楼-- · 2020-07-20 05:12

You could check by doing

if (word.matches("[dgo]*")) {
    ...
}
查看更多
登录 后发表回答