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

99封情书 提交于 2019-12-06 07:12:31

问题


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


回答1:


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;
}



回答2:


You could check by doing

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


来源:https://stackoverflow.com/questions/10567365/how-do-i-find-words-that-only-contain-consist-of-a-given-char-sequence

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!