How to check whether given string is a word

前端 未结 6 1084
礼貌的吻别
礼貌的吻别 2020-12-02 00:51

Hello I am developing a word game where i want to check the user input as valid word or not please suggest the way i can check the given string in android.

Eg . Str

6条回答
  •  时光取名叫无心
    2020-12-02 01:36

    First, download a word list from for example here. Place it in the root directory of your project. Use the following code to check whether a String is part of the word list or not:

    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.Collections;
    import java.util.HashSet;
    import java.util.Set;
    
    public class Dictionary
    {
        private Set wordsSet;
    
        public Dictionary() throws IOException
        {
            Path path = Paths.get("words.txt");
            byte[] readBytes = Files.readAllBytes(path);
            String wordListContents = new String(readBytes, "UTF-8");
            String[] words = wordListContents.split("\n");
            wordsSet = new HashSet<>();
            Collections.addAll(wordsSet, words);
        }
    
        public boolean contains(String word)
        {
            return wordsSet.contains(word);
        }
    }
    

提交回复
热议问题