这是我的浏览方法。我试图搜索“dictionaryEntry”对象的 HashMap ,只查看条目的“word”部分。 (b. 词)。这个想法是,您可以搜索整个字典并返回以给定方法的字符串开头的所有单词。例如,您可以返回以字符串“sto”开头的所有单词。我的想法是迭代 HashMap ,如果单词的子字符串从位置零开始并以输入字符串的长度结束,它将被添加到数组列表中。然后将返回数组列表。
public ArrayList<dictionaryEntry> browse(String s) {
ArrayList<dictionaryEntry> brow = new ArrayList<dictionaryEntry>();
for (dictionaryEntry b : hash.values()) {
if ((b.word.substring(0, s.length())).equals(s)) {
brow.add(new dictionaryEntry(b.word, b.definition));
}
}
return brow;
}
最佳答案
更简单的方法是使用 Java String startsWith API 。该函数将变为以下内容:
public ArrayList<dictionaryEntry> browse(String s) {
ArrayList<dictionaryEntry> brow = new ArrayList<dictionaryEntry>();
for (dictionaryEntry b : hash.values()) {
if (b.word.startsWith(s)) {
brow.add(new dictionaryEntry(b.word, b.definition));
}
}
return brow;
}
关于java - 如何找到以给定字符串开头的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58943818/