我试图写一个program会发现,可以从它使用已经加载到字典中构建的所有单词arrayList从file.sowpodsList是存储为的字典arrayList.我想iterate通过字典中的每个单词,然后将其与之比较string.因为字符串只是一个随机的单词集合,我该怎么做呢?
输入: asdm
输出:( a, mad, sad ....在字典中匹配的任何单词.)
for (int i = 0; i < sowpodsList.size(); i++) {
for (int j = 0; j < sowpodsList.get(i).length(); j++) {
if (sowpodsList.get(i).charAt(j) == )
;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以搜索词典中每个单词的每个字符的数量是否等于输入的字符数量。
ArrayList <String> matches = new ArrayList <String> ();
// for each word in dict
for(String word : sowpodsList) {
// match flag
Boolean nonMatch = true;
// for each character of dict word
for( char chW : word.toCharArray() ) {
String w = Character.toString(chW);
// if the count of chW in word is equal to its count in input,
// then, they are match
if ( word.length() - word.replace(w, "").length() !=
input.length() - input.replace(w, "").length() ) {
nonMatch = false;
break;
}
}
if (nonMatch) {
matches.add( word );
}
}
System.out.println(matches);
Run Code Online (Sandbox Code Playgroud)
示例输出:(我使用的字典文件位于: https: //docs.oracle.com/javase/tutorial/collections/interfaces/examples/dictionary.txt)
Input: asdm
Matches: [ad, ads, am, as, dam, dams, ma, mad, mads, mas, sad]
Run Code Online (Sandbox Code Playgroud)