HeartCore
HeartCore

Reputation: 49

How do I find the longest words in a string?

I want to find the longest words in a given String.

The following code checks for the longest word, but I want every other word with the same length as well.

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

Upvotes: 0

Views: 235

Answers (2)

Abhishek pruthvi V M
Abhishek pruthvi V M

Reputation: 156

try(BufferedReader fileInputReader = new BufferedReader(new FileReader(filePath))){
    String line = fileInputReader.readLine();
    line = line.replaceAll("[^äÄöÖüÜßa-zA-Z ]", "");
    String[] sentence = line.split(" ");
    ArrayList<String> longestWord = new ArrayList<>();
    int maxLength = 1;

    for(int i = 0; i < sentence.length; i++){
      if(sentence[i].length() > maxLength){
        longestword.clear(); 
        longestWord.add(sentence[i]);
        maxLength=sentece[i].length();
      }
    else if(sentence[i].length() == maxLength)
     {
       longestWord.add(sentence[i]);
     }
   }
  System.out.println(longestWord);
  }

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186688

Then you have to use a collection of these longestWords, e.g.

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

Upvotes: 6

Related Questions