【发布时间】:2017-03-31 07:39:47
【问题描述】:
我在 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));
给个提示)
【问题讨论】:
-
那有什么问题?
-
尝试用
"[\\p{P}\\p{S}\\p{Zs}\t]+"分割字符串。如果没有帮助,请定义“单词”。也许更好的方法是匹配"(?>\\p{L}\\p{M}*+)+(?:[-'](?>\\p{L}\\p{M}*+)+)*"。 -
您自己做了什么来发现错误?从Pattern 的Javadoc 开始,您会看到字符类是用小写的
p定义的。例如\p{Punct}而不是\P{Punct}。 -
如果您提供输入文件的样本数据,我们可以更好地帮助您。