w3resource

Java: Reverse every word in a string using methods


46. Reverse Every Word

Write a Java program to reverse every word in a string using methods.

Visual Presentation:

Java String Exercises: Reverse every word in a string using methods


Sample Solution:

Java Code:

// Importing necessary Java utilities.
import java.util.*;

// Define a class named Main.
public class Main {
    
    // Method to reverse each word in a given string.
    public void reverseEachWordInString(String str1) {
        // Split the input string into individual words.
        String[] each_words = str1.split(" ");
        String revString = "";
        
        // Iterate through each word in the array.
        for (int i = 0; i < each_words.length; i++) {
            String word = each_words[i];
            String reverseWord = "";
            
            // Reverse each word character by character.
            for (int j = word.length() - 1; j >= 0; j--) {
                reverseWord = reverseWord + word.charAt(j);
            }
            
            // Build the reversed string by appending the reversed word.
            revString = revString + reverseWord + " ";
        }
        
        // Display the string with reversed words.
        System.out.println(revString);
    }
    
    // Main method to execute the program.
    public static void main(String[] args) {
        // Create an object of the Main class.
        Main obj = new Main();
        String StrGiven = "This is a test string"; // Given input string.
        
        // Display the given input string.
        System.out.println("The given string is: " + StrGiven);
        System.out.println("The string reversed word by word is: ");
        
        // Call the method to reverse each word in the string.
        obj.reverseEachWordInString(StrGiven);
    }
}

Sample Output:

The given string is: This is a test string
The string reversed word by word is: 
sihT si a tset gnirts

Flowchart:

Flowchart: Java String Exercises - Reverse every word in a string using methods



For more Practice: Solve these Related Problems:

  • Write a Java program to reverse every word in a string individually without altering their original order.
  • Write a Java program to reverse each word of a sentence and then concatenate them into a single reversed string.
  • Write a Java program to reverse words in a string by splitting on spaces and then applying a reverse function to each word.
  • Write a Java program to reverse each word in a sentence and then print the lengths of the reversed words.

Go to:


PREV : Reverse Words in String.
NEXT : Rearrange String with Distance.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.