Java Program to Reverse Each Word of a String

Write a java program to reverse each word of a string without changing the order of the word..

Suppose, If an input string is Java Programming then the output string should be avaJ gnimmargorP.

Example –

Input: Java Programming

Output: avaJ gnimmargorP

Java Program to Reverse Each Word of a String

In this tutorial, I am going to explain multiple approaches to solve this problem.

Java Program to Reverse Each Word of a String

The easiest way is to split the input string into array of words is by using split() method. The string split() method splits a given string around matches of the given regular expression. After splitting, it returns a String array. In this example, we are splitting the string around space.

Here are the steps to solve this problem –

i) Split the string using split() method. Once string is split, we get array of words.

ii) Traverse an array and take each word at a time.

iii) Reverse a word and append to the final string.

iv) Finally, print or return the result.

Find duplicate characters in a string

Check whether two strings are anagram of each other

Reverse Each Word In String without using Inbuilt Functions

In this example, i am going to use stack to solve this problem.

We can also reverse words of a string using stack data structure. In a stack, the element which we push at last is the first element to be popped out (LIFO). We can use this property of a stack to solve this problem.

Implement queue using two stacks

Here are the steps –

i) Declare a stack which store the value of character type.

ii) Traverse a string and push each character in a stack until the space is encountered. When space is encountered popped all the characters from a stack unitl it is empty. Append the reverse words in a string.

The time and space complexity of this approach is O(n).

Reverse Each Word in a String in Java 8 Using Lambda

In this example, i am going to write a code to solve this problem using Java 8 lambda.

Video Tutorial

Reverse each word of a string video tutorial

Tagged , , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.