简体   繁体   中英

How to find the longest word in a given string?

In a given string, I want to find the longest word then print it in the console.

The output I get is the second longest word ie "Today" , but I should get "Happiest" instead.
May I know what I am doing wrong? Is there a better/different way to find the longest word in a string?

public class DemoString {
    public static void main(String[] args) {
        String s = "Today is the happiest day of my life";
        String[] word = s.split(" ");
        String longword = " ";
        for (int i = 0; i < word.length; i++)
            for (int j = 1 + i; j < word.length; j++)
                if (word[i].length() >= word[j].length())
                    longword = word[i];

        System.out.println(longword + " is the longest word with " + longword.length() + " characters.");
        System.out.println(rts.length());
    }
}

Here is a one-liner you can use with Java 8:

import java.util.Arrays;
import java.util.Comparator;

public class Main {
  public static void main(String[] args) {
    String s = "Today is the happiest day of my life";
    String longest = Arrays.stream(s.split(" ")).max(Comparator.comparingInt(String::length)).orElse(null);
    System.out.println(longest);
  }
}

Output:

happiest

Try it here!

instead it should be:

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

// the below Java Program will find Smallest and Largest Word in a String

class SmallestAndLargestWord 
{ 

    static String minWord = "", maxWord = ""; 

    static void minMaxLengthWords(String input)  
    { 
        // minWord and maxWord are received by reference  
        // and not by value 
        // will be used to store and return output 
        int len = input.length(); 
        int si = 0, ei = 0; 
        int min_length = len, min_start_index = 0, 
              max_length = 0, max_start_index = 0; 

        // Loop while input string is not empty 
        while (ei <= len)  
        { 
            if (ei < len && input.charAt(ei) != ' ') 
            { 
                ei++; 
            }  
            else
            { 
                // end of a word 
                // find curr word length 
                int curr_length = ei - si; 

                if (curr_length < min_length)  
                { 
                    min_length = curr_length; 
                    min_start_index = si; 
                } 

                if (curr_length > max_length)  
                { 
                    max_length = curr_length; 
                    max_start_index = si; 
                } 
                ei++; 
                si = ei; 
            } 
        } 

        // store minimum and maximum length words 
        minWord = input.substring(min_start_index, min_start_index + min_length); 
        maxWord = input.substring(max_start_index, max_length); 
    } 

    // Driver code 
    public static void main(String[] args) 
    { 
        String a = "GeeksforGeeks A Computer Science portal for Geeks"; 

        minMaxLengthWords(a); 

        // to take input in string use getline(cin, a); 
        System.out.print("Minimum length word: "
                + minWord 
                + "\nMaximum length word: "
                + maxWord); 
    } 
} 

**

Input : "GeeksforGeeks A computer Science portal for Geeks"
Output : Minimum length word: A
         Maximum length word: GeeksforGeeks

**

    String s= "Today is the happiest day of my life by vijayakumar";
           String [] word = s.split(" ");
    String maxlethWord = "";
    for(int i = 0; i < word.length; i++){
            if(word[i].length() >= maxlethWord.length()){
                  maxlethWord = word[i];
            } 
    }
     System.out.println(maxlethWord);  

I haven't seen an answer where you create a list of the words. So here is another way to solve the problem:

String s = "Today is the happiest day of my life";;
List<String> strings = Arrays.asList(s.split(" "));    
String biggestWord = Collections.max(strings, Comparator.comparing(String::length));
System.out.println(biggestWord);

Output:

happiest

You can try like ,

  String s="Today is the happiest day of my life";
  String[] word=s.split(" ");
  String rts=" ";
  for(int i=0;i<word.length;i++){
     if(word[i].length()>=rts.length()){
       rts=word[i];
     }
  }
  System.out.println(rts);
  System.out.println(rts.length());

Try this one.

   public static void main( String[] args )
    {
        String s = "Today is the happiest day of my life";
        String[] word = s.split( " " );
        String rts = " ";

        for ( int i = 0; i < word.length; i++ )
        {
            if ( word[i].length() > rts.length() )
                rts = word[i];

        }
        System.out.println( rts );
    }
for(int i=0;i<word.length;i++){
            for(int j=0;j<word.length;j++){
                if(word[i].length()>=word[j].length()){
                   if(word[j].length()>=rts.length()) {
                      rts=word[j];
                   }
                } else if(word[i].length()>=rts.length()){
                   rts=word[i];
                }

            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM