我有一个关于如何在 java 中做一些涉及字符串和列表的事情的问题。我希望能够输入一个字符串,例如
“啊”
使用扫描器类,程序必须返回其中包含三个 a 的最短单词。因此,例如,有一个包含数千个单词的文本文件要与输入进行检查,如果其中包含三个 a,那么它是候选者,但现在它是最短的,只返回那个。您究竟是如何比较并查看输入的字母是否在一个充满单词的文本文件的所有单词中?
尝试这个,
while ((input = br.readLine()) != null)
{
if(input.contains(find)) // first find the the value contains in the whole line.
{
String[] splittedValues = input.split(" "); // if the line contains the given word split it all to extract the exact word.
for(String values : splittedValues)
{
if(values.contains(find))
{
System.out.println("all words : "+values);
}
}
}
}
最简单的方法是使用String.contains()
一个检查长度的循环:
String search = "aaa"; // read user input
String fileAsString; // read in file
String shortest = null;
for (String word : fileAsString.split("\\s*")) {
if (word.contains(search) && (shortest == null || word.length() < shortest.length())) {
shortest = word;
}
}
// shortest is either the target or null if no matches found.