java - 如何找到字符串中最长的单词?

标签 java string

我想找到给定字符串最长的单词

以下代码检查最长的单词,但我希望所有其他单词也具有相同的长度

try (BufferedReader fileInputReader = new BufferedReader(new FileReader(filePath))){
    String line = fileInputReader.readLine();

    line = line.replaceAll("[^äÄöÖüÜßa-zA-Z ]", "");
    String[] sentence = line.split(" ");
    String longestWord = "";

    for (int i = 0; i < sentence.length; i++) {
        if (sentence[i].length() > longestWord.length()) {
            longestWord = sentence[i];
        }
    }

    System.out.println(longestWord);
}

最佳答案

然后您必须使用这些最长单词集合,例如

  ArrayList<String> longestWords = new ArrayList<String>();
  int longestWordLength = 0;

  for (int i = 0; i < sentence.length; i++) {
      if (sentence[i].length() > longestWordLength) { // longer
          longestWordLength = sentence[i].length();
          longestWords.clear();
          longestWords.add(sentence[i]);       
      } 
      else if (sentence[i].length() == longestWordLength) { // same length
          longestWords.add(sentence[i]);       
      }
  }

  for (int i = 0; i < longestWords.size(); ++i) 
      System.out.println(longestWords.get(i));

关于java - 如何找到字符串中最长的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58502164/

相关文章:

java - 自定义 TableModel - 所有查询的模型相同

string - 有没有办法表示在 YAML 文档中的多行上没有任何空格的长字符串?

python - 如何在python中修剪字符串的n个字符?

java - 在 Android Studio 中动态创建按钮时遇到问题

java - 微服务架构 DVD 租赁应用

java - 如何使用 libgdx 获取手机语言?

java - java中合并多个Map并用不同的key区分它们的值

java - 使用 with parseint 将 String 转换为 int

string - C++/CLI 将 System::String 转换为 const char*

c - 在 C 中检查给定字符串是否为回文的有效方法