如何检查给定的字符串是否为单词

您好我正在开发一个文字游戏,我想检查用户输入是否有效的单词请建议我可以检查android中的给定字符串的方式。

例如。 String s =“asfdaf”我想检查它是否是有效的。

有一些可能的解决方案,有些是以下几种

使用Web Dictionary API

https://developer.oxforddictionaries.com/

http://googlesystem.blogspot.com/2009/12/on-googles-unofficial-dictionary-api.html

http://www.dictionaryapi.com/

如果您更喜欢本地解决方案

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; class WordChecker { public static boolean check_for_word(String word) { // System.out.println(word); try { BufferedReader in = new BufferedReader(new FileReader( "/usr/share/dict/american-english")); String str; while ((str = in.readLine()) != null) { if (str.indexOf(word) != -1) { return true; } } in.close(); } catch (IOException e) { } return false; } public static void main(String[] args) { System.out.println(check_for_word("hello")); } } 

这使用在所有Linux系统上找到的本地单词列表来检查单词

首先,从here下载单词列表。 将其放在项目的根目录中。 使用以下代码检查String是否是单词列表的一部分:

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

我会存储一本字典并在那里进行查找。 如果单词存在于词典中,则它是有效的。

你可以在这里找到一些关于如何做到这一点的线索: Android词典应用程序

zeitue说:

 import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; class WordChecker { public static boolean check_for_word(String word) { // System.out.println(word); try { BufferedReader in = new BufferedReader(new FileReader( "/usr/share/dict/american-english")); String str; while ((str = in.readLine()) != null) { if (str.indexOf(word) != -1) { return true; } } in.close(); } catch (IOException e) { } return false; } public static void main(String[] args) { System.out.println(check_for_word("hello")); } } 

但这只适用于linux。 如果你想在Mac上同样的东西改变路径

 /usr/share/dict/american-english 

 /usr/share/dict/web2 

我没有在Windows上试过这个,但如果有人知道下面的评论

 if(s.equals("word from dictionary in loop"){ //action } 

它也很好

 s = s.toLowerCase(); 

所以无论口袋妖怪是多么“口袋妖怪”

您可以尝试使用此代码进行基本validation

 import java.util.Scanner; public class InputValidation { public static void main(String[] args) { String input; try { System.out.println("Enter the input"); Scanner s = new Scanner(System.in); input = s.next(); if(input.matches(".*\\d.*")){ System.out.println(" Contains digit only"); } else{ System.out.println(" Only String/words found"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }