Introduction
Finding the longest word in a string is a useful task in text processing. This task helps you practice string manipulation, splitting strings into words, and comparing lengths of words. This guide will walk you through writing a Java program that identifies the longest word in a given string.
Problem Statement
Create a Java program that:
- Prompts the user to enter a string.
- Splits the string into words.
- Identifies and displays the longest word in the string.
Example:
- Input: "Java programming language is powerful"
- Output: "Longest word: programming"
Solution Steps
- Read the String: Use the Scannerclass to take the string as input from the user.
- Split the String into Words: Use the split()method to break the string into words.
- Identify the Longest Word: Use a loop to compare the lengths of the words and find the longest one.
- Display the Longest Word: Print the longest word in the string.
Java Program
// Java Program to Find the Longest Word in a String
// Author: https://www.rameshfadatare.com/
import java.util.Scanner;
public class LongestWordFinder {
    public static void main(String[] args) {
        // Step 1: Read the string from the user
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("Enter a string: ");
            String input = scanner.nextLine();
            
            // Step 2: Split the string into words
            String[] words = input.split("\\s+");
            
            // Step 3: Identify the longest word
            String longestWord = "";
            for (String word : words) {
                if (word.length() > longestWord.length()) {
                    longestWord = word;
                }
            }
            
            // Step 4: Display the longest word
            System.out.println("Longest word: " + longestWord);
        }
    }
}
Explanation
Step 1: Read the String
- The Scannerclass is used to read a string input from the user. ThenextLine()method captures the entire line as a string.
Step 2: Split the String into Words
- The split()method is used to divide the string into words based on whitespace. The regex\\s+handles multiple spaces between words.
Step 3: Identify the Longest Word
- A forloop iterates through each word in the array.
- The ifstatement checks whether the current word is longer than the previously found longest word. If it is, thelongestWordvariable is updated.
Step 4: Display the Longest Word
- The program prints the longest word found in the string using System.out.println().
Output Example
Example:
Enter a string: Java programming language is powerful
Longest word: programming
Conclusion
This Java program demonstrates how to find and display the longest word in a user-input string. It covers essential concepts such as string manipulation, using loops for comparison, and handling arrays, making it a valuable exercise for beginners learning Java programming.