Longest word in string java

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 i.e "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());
    }
}

0009laH's user avatar

0009laH

1,90612 silver badges26 bronze badges

asked Apr 6, 2017 at 9:59

Suraj's user avatar

Here is a «one-liner» you can use with the Java 8 streams API:

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 out here.

answered Apr 6, 2017 at 10:29

Sash Sinha's user avatar

Sash SinhaSash Sinha

17.6k3 gold badges22 silver badges40 bronze badges

2

// 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

**

answered Apr 22, 2019 at 5:54

TanvirChowdhury's user avatar

instead it should be:

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

okandas's user avatar

okandas

11.2k2 gold badges15 silver badges17 bronze badges

answered Apr 6, 2017 at 10:03

tt_emrah's user avatar

tt_emrahtt_emrah

1,0431 gold badge8 silver badges19 bronze badges

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

answered Jun 4, 2018 at 9:27

Vivekanandan V's user avatar

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

answered Nov 2, 2020 at 14:07

Krayzzee's user avatar

KrayzzeeKrayzzee

862 silver badges5 bronze badges

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

answered Apr 6, 2017 at 10:07

MSD's user avatar

MSDMSD

1,40912 silver badges25 bronze badges

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

answered Jun 4, 2018 at 9:40

Supun Dharmarathne's user avatar

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

            }
        }

answered Apr 6, 2017 at 10:23

Madhavi's user avatar

MadhaviMadhavi

4742 gold badges7 silver badges19 bronze badges

Following is my code:

 String LongestWord(String a)
{
    int lw=0;
    int use;
    String lon="";
    while (!(a.isEmpty()))
    {
        a=a.trim();
        use=a.indexOf(" ");
        if (use<0)
        {
            break;
        }
        String cut=a.substring(0,use);
        if(cut.length()>lw)
        {
            lon=cut;
        }
        lw=lon.length();
        a=a.replace(cut," ");
    }
    return lon;
}

The problem is that when I input a string like,
«a boy is playing in the park»

it returns the longest word as «ying» because when it replaces ‘cut’ with » » for the first time, it removes all the ‘a’-s too, such that it becomes
» boy is pl ying in the p rk» after the first iteration of the loop

Please figure out what’s wrong?

Thanks in advance!

asked May 11, 2016 at 15:21

Shinjinee Maiti's user avatar

Shinjinee MaitiShinjinee Maiti

1351 gold badge2 silver badges10 bronze badges

2

You have already known the problem: the program does unwanted replacement.

Therefore, stop doing replacement.
In this program, the word examined is directly cut instead of using the harmful replacement.

String LongestWord(String a)
{
    int lw=0;
    int use;
    String lon="";
    while (!(a.isEmpty()))
    {
        a=a.trim();
        use=a.indexOf(" ");
        if (use<0)
        {
            break;
        }
        String cut=a.substring(0,use);
        if(cut.length()>lw)
        {
            lon=cut;
        }
        lw=lon.length();
        a=a.substring(use+1); // cut the word instead of doing harmful replacement
    }
    return lon;
}

answered May 11, 2016 at 15:28

MikeCAT's user avatar

You can use the split function to get an array of strings.

Than cycle that array to find the longest string and return it.

 String LongestWord(String a) {
    String[] parts = a.split(" ");
    String longest = null;
    for (String part : parts) {
        if (longest == null || longest.length() < part.length()) {
            longest = part;
        }
    }
    return longest;
 }

answered May 11, 2016 at 15:29

Davide Lorenzo MARINO's user avatar

I would use arrays:

String[] parts = a.split(" ");

Then you can loop over parts, for each element (is a string) you can check length:

parts[i].length()

and find longest one.

answered May 11, 2016 at 15:34

Francesco Serra's user avatar

0

I would use a Scanner to do this

String s = "the boy is playing in the parl";
int length = 0;
String word = "";
Scanner scan = new Scanner(s);
    while(scan.hasNext()){

        String temp = scan.next();
        int tempLength = temp.length();

        if(tempLength > length){
            length = tempLength;
            word = temp;
        }
    }
}

You check the length of each word, if it’s longer then all the previous you store that word into the String «word»

answered May 11, 2016 at 15:26

Alessandro Dal Gobbo's user avatar

Another way uses Streams.

    Optional<String> max = Arrays.stream("a boy is playing in the park"
            .split(" "))
            .max((a, b) -> a.length() - b.length());
    System.out.println("max = " + max);

answered May 11, 2016 at 15:37

OldCurmudgeon's user avatar

OldCurmudgeonOldCurmudgeon

64.1k16 gold badges119 silver badges211 bronze badges

0

if you are looking for not trivial Solution ,you can solve it without using split or map but with only one loop

static String longestWorld(String pharagragh) {
    int maxLength = 0;
    String word=null,longestWorld = null;
    int startIndexOfWord = 0, endIndexOfWord;
    int wordLength = 0;
    for (int i = 0; i < pharagragh.length(); i++) {
        if (pharagragh.charAt(i) == ' ') {
            endIndexOfWord = i;
            wordLength = endIndexOfWord - startIndexOfWord;
            word = pharagragh.substring(startIndexOfWord, endIndexOfWord);
            startIndexOfWord = endIndexOfWord + 1;
            if (wordLength > maxLength) {
                maxLength = wordLength;
                longestWorld = word;
            }
        }
    }
    return longestWorld;
}

now lets test it

System.out.println(longestWorld("Hello Stack Overflow Welcome to Challenge World"));// output is Challenge

answered Sep 28, 2016 at 20:24

Basheer AL-MOMANI's user avatar

Try :

package testlongestword;

/**
 *
 * @author XOR
 */
public class TestLongestWord{
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        System.out.println(LongestWord("a boy is playing in the park"));
    }

    public static String LongestWord(String str){
        String[] words = str.split(" ");
        int index = 0;
        for(int i = 0; i < words.length; ++i){
            final String current = words[i];
            if(current.length() > words[index].length()){
                index = i;
            }
        }
        return words[index];
    }
}

answered Sep 28, 2016 at 21:11

XOR's user avatar

XORXOR

5,6962 gold badges15 silver badges10 bronze badges

You have to write a program in Java which will find the longest word in the String.
For eg.
Input: That building is very tall.
Output: building
In above example «building» is the longest word in the given string i.e «That building is very tall.»

Find the longest word in a String using java

public class FindLarge {
private String longestWord;

public String longestWord(String sen) {

String arr[] = sen.split(» «); // seperates each word in the string and stores it in array

longestWord = arr[0]; // Assume first word to be the largest word

for (String a : arr)
if (longestWord.length() < a.length()) // check length of each word
longestWord = a;

return longestWord;

}

public static void main(String[] args) {

FindLarge fl=new FindLarge();

String longestWord=fl.longestWord(«Hello Welcome to Java»); // string to be checked

System.out.println(«Longest Word: «+ longestWord); // Final Output

}

}

Longest-Word-In-A-String

The program «LongestWordInAText.java» determines and prints the longest words, along with it’s length, present in the given String.

The class «LongestWordInATextTest.java» uses JUnit-4 to test the LongestWordInAText.java program.

To run the program through Command Prompt on Windows:

  1. Open Windows cmd
  2. Change the path:
    cd path_location_to_the_file
  3. To compile the java class:
    javac LongestWordInAText.java
  4. To run the java program:
    java LongestWordInAText

To test the program through Command Prompt on Windows:

  1. Open Windows cmd
  2. Download the junit-4.12.jar and the hamcrest-core-1.3 jar from junit.org
  3. Set the path for the above jar files:
    set CLASSPATH=%CLASSPATH%;C:(path to junit jar)junit-4.12.jar;C:(path to hamcrest jar)hamcrest-core-1.3.jar;C:path_to_the_test_file
  4. To compile the test class:
    javac LongestWordInATextTest.java
  5. To run the test class:
    java org.junit.runner.JUnitCore LongestWordInATextTest

The programs could also be Run using Eclipse IDE performing the following:

  1. Create a new Java project on Eclipse:
    File->New->Java Project

  2. Create a Java class under the default package:
    Right click on the default package->New-> Java class

  3. Name the java class as «LongestWordInAText.java» and copy paste the contents of the LongestWordInAText.java in it

  4. Create a Junit Test class:
    Right click on the default package->New-> Junit Test Case

  5. Name the java class as «LongestWordInATextTest.java» and copy paste the contents of the LongestWordInATextTest.java in it

  6. Add junit-4 jar files to the library

  7. To execute the programs individually:
    click on Run from the toolbar and select Run

ASSUMPTIONS:

  1. If there are multiple words of the same maximum length, the program returns all the words of equal length
  2. The program does not consider spaces as characters
  3. The program strips punctuations from the words

Like this post? Please share to your friends:
  • Longest word in latin
  • Longest word in italian
  • Longest word in germany
  • Longest word in english starting with a
  • Longest word in english said