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

Here’s a breakdown of the program:

  1. Define the main method:
    • The entry point of the program is the main method.
  2. Initialize variables:
    • The input string str is initialized with the value “My n@me is 12Rahul”.
    • An empty string result is created to store the final reversed string.
    • An array py is created by splitting the input string into words using the space character as a delimiter.
    • An integer counter is initialized to keep track of special characters and numbers within each word.
  3. Loop through the words:
    • The program iterates through each word in the py array using a for loop.
  4. Reverse characters in each word:
    • The program iterates through each character of the current word in reverse order using another for loop.
  5. Preserve special characters and numbers:
    • If the current character is not a digit (i.e., a character or special character), it is appended to the result string.
    • If the current character is a digit, it means it is a number, so it is appended to the result string, and the counter is incremented to skip the number during the next iteration.
  6. Add space between words:
    • After reversing all characters of a word, a space is appended to the result string to separate the words.
  7. Print the reversed string:
    • After all the words are processed, the final reversed string is printed.

Overall, this program reverses the characters within each word of the input string while leaving special characters and numbers in their original positions. The output will be “yM em@n si 12luhaR”, which is each word of the input string reversed while maintaining the positions of special characters and numbers.

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

Here’s a breakdown of the program:

  1. Import required Java classes:
    • The program imports Collectors and Stream classes from the java.util.stream package.
  2. Define the main method:
    • The entry point of the program is the main method.
  3. Initialize variables and process the input string:
    • The input string str is initialized with the value “My n@me is 12Rahul”.
    • The program splits the input string into words using the space character as a delimiter and converts it into a Stream<String>.
    • The Stream<String> is then processed to reverse the characters within each word using the reverse method.
  4. The reverse method:
    • The reverse method takes a character array as input.
    • It uses two pointers, left and right, to traverse the array from both ends.
    • While traversing, it ignores digits (numbers) and swaps characters that are not digits to reverse the word.
    • The method returns the reversed word as a string.
  5. Collect the results and print the reversed string:
    • The reversed words are collected back into a single string, with spaces as separators.
    • The final reversed string is then printed.

Overall, this program effectively reverses the characters within each word of the input string while leaving special characters and numbers in their original positions. The output will be “yM em@n si 12luhaR”, which is each word of the input string reversed while maintaining the positions of special characters and numbers. The use of Stream API makes the code more concise and expressive.

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