In this section you will learn how to get the longest word in the string
In this section you will learn how to get the longest word in the stringIn this section you will learn how to get the longest word in the string . Here we are going to find the longest word in a given string. We specify the string and then split the string using split() method which divide the string, and assign the first word of the string to the a new string and compare remaining words of string with the first word. If any of the remaining words is bigger than the first word of the string, then the bigger word overwrites the first word and the length of that string is found. If the compared word is not bigger, the first word will be printed as the largest string. Here is the program below:
import java.util.Scanner; public class LargestWord { public static void main(String args[]) { System.out.println(); Scanner sc = new Scanner( System.in ); String line; String largest; String currentWord; String wordsLine[]; System.out.println("Please enter the line of text."); line = sc.nextLine(); line = line.trim(); if (line.equals( "" )) { System.out.println("You have not entered a any words."); return; } wordsLine = line.split(" "); largest = wordsLine[0]; for (int i = 1; i < wordsLine.length; i++) { currentWord = wordsLine[i]; if (currentWord.length() > largest.length()) { largest = currentWord; } } System.out.println( "The largest word is " + largest + " with a length of " + largest.length()); } }
Output : After compiling and executing the above program.