Home Tutorial Java Core A program to find the largest word in String

 
 

A program to find the largest word in String
Posted on: June 7, 2013 at 12:00 AM
Advertisement
In this section you will learn how to get the longest word in the string

A program to find the largest word in String

In 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.

Download  SourceCode

Advertisement

Related Tags for A program to find the largest word in String:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 7, 2013

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com