WAP to Reverse Words Without Changing Order & Digits Position

Reverse Words Without Changing Order & Digits Position: This Java program takes an input string and reverses the characters within each word while preserving the order of numbers. The program uses nested loops to achieve this.

Reverse Words Without Changing Digits Position

package com.softwaretestingo.interviewprograms;
public class InterviewPrograms28 
{
	/*
	 * Input String // My n@me is 12Rahul 
	 * Output String // yM em@n si 12luhaR 
	 * Only charcters should be Character, special characters and numbers should be displayed as it is.
	 */
	public static void main(String[] args) 
	{
		String str = "My n@me is 12Rahul";
		String result="";
		String[] py = str.split(" ");
		int counter=0;
		for(int i=0;i<py.length;i++) 
		{
			String tem = py[i];
			for(int gg = tem.length()-1; gg>=0; gg--) 
			{
				if(!Character.isDigit(tem.charAt(counter))) 
				{
					result = result + tem.charAt(gg+counter);
				}
				else
				{
					result = result + tem.charAt(counter);
					counter++;
				}
			}
			result = result+ " ";
			counter=0;
		}
		System.out.println(result);
	}
}

Output

yM em@n si 12luhaR

Alternative Way 1:

This Java program takes an input string and reverses the characters within each word while preserving the order of special characters and numbers. It utilizes Java 8 Stream API to achieve this.

package com.softwaretestingo.interviewprograms;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class InterviewPrograms28_1 
{
	/*
	 * Input String // My n@me is 12Rahul 
	 * Output String // yM em@n si 12luhaR 
	 * Only charcters should be Character, special characters and numbers should be displayed as it is.
	 */
	public static void main(String[] args) 
	{
		String str = "My n@me is 12Rahul";
		String resultString = Stream.of(str.split(" ")).map(String::toCharArray).map(InterviewPrograms28_1::reverse)
				.collect(Collectors.joining(" "));
		System.out.println(resultString);
	}
	public static String reverse ( char str [ ] )
	{
		int left = 0 , right = str.length - 1 ;
		while ( left< right ) 
		{
			// Ignore numbers characters
			if ( Character.isDigit ( str [left]))
				left ++ ;
			else if ( Character.isDigit ( str [right]))
				right-- ;
			else {
				char tmp = str [ left ] ;
				str [ left ] = str [ right ] ;
				str [ right ] = tmp ;
				left ++ ;
				right-- ;
			}
		}
		return new String ( str ) ;
	}
}

Output

yM em@n si 12luhaR

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