首页 > 解决方案 > 如何找到字符串中最长的单词?

问题描述

我想在给定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);
}

标签: javastring

解决方案


然后你必须使用这些的集合longestWords,例如

  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));

推荐阅读