Java Program to Reverse Each Word of a String

Introduction

Reversing each word in a string is a common text manipulation task that can be useful in various applications such as text processing, cryptography, and data analysis. In this blog post, we will explore how to write a Java program to reverse each word in a given string.

Approach

To reverse each word in a string, we can:

  1. Split the string into words.
  2. Reverse each word individually.
  3. Reassemble the reversed words into a final string.

Example Program

Here is a Java program that demonstrates how to reverse each word in a string.

Example Code:

public class ReverseEachWord {
    public static void main(String[] args) {
        String input = "Java is great and fun";

        // Call the method to reverse each word
        String result = reverseWords(input);

        // Print the result
        System.out.println("Original String: " + input);
        System.out.println("String with each word reversed: " + result);
    }

    // Method to reverse each word in the string
    public static String reverseWords(String input) {
        // Split the string into words
        String[] words = input.split("\\s+");
        StringBuilder result = new StringBuilder();

        // Reverse each word and append to the result
        for (String word : words) {
            result.append(new StringBuilder(word).reverse().toString()).append(" ");
        }

        // Convert StringBuilder to string and trim the trailing space
        return result.toString().trim();
    }
}

Output:

Original String: Java is great and fun
String with each word reversed: avaJ si taerg dna nuf

Explanation:

  1. ReverseEachWord Class:

    • The ReverseEachWord class contains the main method and a helper method reverseWords.
  2. reverseWords Method:

    • This method takes a string as input and returns a new string with each word reversed.
    • The input string is split into words using split("\\s+"), which matches one or more whitespace characters.
    • A StringBuilder is used to build the result string.
    • Each word is reversed using new StringBuilder(word).reverse().toString() and appended to the result.
    • The trailing space is removed by calling trim() on the final result string.

2. Using Java 8 Streams

Java 8 Streams provide a modern and concise way to reverse each word in a string. This approach leverages the power of functional programming.

Example:

import java.util.Arrays;
import java.util.stream.Collectors;

public class ReverseEachWordWithStreams {
    public static void main(String[] args) {
        String input = "Java is great and fun";

        // Call the method to reverse each word using streams
        String result = reverseWords(input);

        // Print the result
        System.out.println("Original String: " + input);
        System.out.println("String with each word reversed using streams: " + result);
    }

    // Method to reverse each word in the string using streams
    public static String reverseWords(String input) {
        return Arrays.stream(input.split("\\s+"))
                     .map(word -> new StringBuilder(word).reverse().toString())
                     .collect(Collectors.joining(" "));
    }
}

Output:

Original String: Java is great and fun
String with each word reversed using streams: avaJ si taerg dna nuf

Explanation:

  1. ReverseEachWordWithStreams Class:

    • The ReverseEachWordWithStreams class contains the main method and a helper method reverseWords.
  2. reverseWords Method:

    • This method takes a string as input and returns a new string with each word reversed.
    • The input string is split into a stream of words using Arrays.stream(input.split("\\s+")).
    • Each word in the stream is reversed using map(word -> new StringBuilder(word).reverse().toString()).
    • The reversed words are joined back into a single string using Collectors.joining(" ").

Complete Example Program

Here is a complete program that demonstrates both methods to reverse each word in a string.

Example Code:

import java.util.Arrays;
import java.util.stream.Collectors;

public class ReverseWordsExample {
    public static void main(String[] args) {
        String input = "Java is great and fun";

        // Using Traditional Approach
        String resultTraditional = reverseWordsTraditional(input);
        System.out.println("Using Traditional Approach:");
        System.out.println("Original String: " + input);
        System.out.println("String with each word reversed: " + resultTraditional);

        // Using Java 8 Streams
        String resultStreams = reverseWordsStreams(input);
        System.out.println("\nUsing Java 8 Streams:");
        System.out.println("Original String: " + input);
        System.out.println("String with each word reversed: " + resultStreams);
    }

    // Method to reverse each word in the string using traditional approach
    public static String reverseWordsTraditional(String input) {
        String[] words = input.split("\\s+");
        StringBuilder result = new StringBuilder();

        for (String word : words) {
            result.append(new StringBuilder(word).reverse().toString()).append(" ");
        }

        return result.toString().trim();
    }

    // Method to reverse each word in the string using streams
    public static String reverseWordsStreams(String input) {
        return Arrays.stream(input.split("\\s+"))
                     .map(word -> new StringBuilder(word).reverse().toString())
                     .collect(Collectors.joining(" "));
    }
}

Output:

Using Traditional Approach:
Original String: Java is great and fun
String with each word reversed: avaJ si taerg dna nuf

Using Java 8 Streams:
Original String: Java is great and fun
String with each word reversed: avaJ si taerg dna nuf

Conclusion

Reversing each word in a string can be accomplished in multiple ways in Java. The traditional approach is straightforward and easy to understand, while Java 8 Streams provides a modern, functional way to handle the task. Both methods ensure that each word is reversed individually, resulting in a string with reversed words but the original word order intact.

By understanding these different methods, you can choose the one that best fits your needs and coding style. Happy coding!

Comments