How To Reverse Each Word Of A String In Java?

Example :

If Input is = "Java"

Output should be = "avaj"

How??

-> Split the given inputString into words using split() method. Then take each individual word, reverse it and append to reverseString. Finally print reverseString.

Java Code :-

public class ReverseEachWord
{
    static void reverseEachWordOfString(String inputString)
    {
        String[] words = inputString.split(" ");
        
        String reverseString = "";
        
        for (int i = 0; i < words.length; i++)
        {
            String word = words[i];
            
            String reverseWord = "";
            
            for (int j = word.length()-1; j >= 0; j--)
            {
                reverseWord = reverseWord + word.charAt(j);
            }
            
            reverseString = reverseString + reverseWord + " ";
        }
        
        System.out.println(inputString);
        
        System.out.println(reverseString);
        
        System.out.println("-------------------------");
    }
    
    public static void main(String[] args)
    {
        reverseEachWordOfString("Java");
        
        reverseEachWordOfString("Java Program");
        
        reverseEachWordOfString("I am string");
        
        reverseEachWordOfString("Reverse Me");
    }
}
OUTPUT :-
Java
avaJ
*************
Java Program
avaJ margorP
*************
I am string
I ma gnirts
*************
Reverse Me
esreveR eM
*************

 

Author: Fabian Ros
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments