WAP to Reverse Words without Changing Order & Split

Reverse Words without Changing Order & Split: This Java program takes an input string and reverses the order of characters within each word while keeping the words themselves in the same order. The program uses a stack data structure to achieve this.

Reverse Words without Changing Order & Split

package com.softwaretestingo.interviewprograms;
import java.util.Stack;
public class InterviewPrograms27 
{
	/*
	 * Input: reverse me without split 
	 * Output: esrever em tuohtiw tilps
	 */
	public static void main(String[] args) 
	{
		String str = "reverse me without split";
		Stack st=new Stack<Character>();
		for (int i = 0; i < str.length(); ++i) 
		{
			if (str.charAt(i) != ' ')
				st.push(str.charAt(i));
			else {
				while (st.empty() == false) 
				{
					System.out.print(st.pop());
				}
				System.out.print(" ");
			}
		}
		while (st.empty() == false) 
		{
			System.out.print(st.pop());
		}
	}
}

Output

esrever em tuohtiw tilps

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment