java - 将行分割为单词数组

标签 java regex swing split

我正在 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/

相关文章:

java - Hibernate Envers 审计 @Embedded 内有基本类型 throws 无法在获取时将字段设置为空值

regex - 正则表达式匹配中的固定字符数

java - 计时器需要很长时间才能启动

swing - 如何实例化一个空的 JTable?

java - 如何将数据从 JTextField 发送到 JList?

java - javax.security.cert.X509Certificate 和 java.security.cert.X509Certificate 之间不兼容

java - 通过分割或使用正则表达式将 ID 与另一个字符串进行匹配

python - 正则表达式 django url

c++ - POSIX 扩展正则表达式 - 不包含 X 但包含 Y (std::regex c++11)

java - Swing 应用程序不运行