我正在 txt.file 中查找最长和最短的单词。 但我总是看结果
File Path: there it's ok.
The longest word: *empty*
The shortest word: *empty*
Task complete...
代码:
List<String> lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
String max = "", min = "BlaBlaBlaBlaBlaBlaBla";
// We take a single line
for(String line: lines){
// Break the next line through the regular to an array of words
List<String> words = Arrays.asList(line.split("\\P{Punct}\\P{Space}"));
String tempMax = Collections.max(words);
max = max.length() < tempMax.length() ? tempMax : max;
String tempMin = Collections.min(words);
min = min.length() > tempMin.length() ? tempMin : min;
}
textArea.setText(String.format(
"File Path: %s\n" +
"The longest word: %s\n" +
"The shortest word: %s\n" +
"Task complete...", fileName, max, min));
给个提示)
最佳答案
问题似乎出在这里:
String tempMax = Collections.max(words);
Collections.max
返回给定集合的最大元素。
对于List<String>
最大元素将为您提供列表中按字母顺序最后的单词。
例如在此列表中:
new String[] {"food", "zz", "abcdef", "zoo"}
它将找到"zz"
作为最大元素。
此外,您的正则表达式用于解决问题 \\P{Punct}\\P{Space}
不正确。
-
\\P{Punct}\\P{Space}
表示非标点符号单词后跟一个空格。
您的问题下面有一些非常有用的评论,建议了正确的拆分方法。
最低使用量:[\\p{P}\\P{ZS}]+
用于分割。
关于java - 将行分割为单词数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43135178/