WAP to Reverse Order Of String By Preserving Space Position?

This Java program aims to reverse the order of words in a given input string while preserving the positions of spaces.

If you need more java program interview questions and answers for experienced, then you can follow this link.

Reverse Order Of String By Preserving Space Position

[ Today is January 5th –> 5thja nu aryisTo day ]

Reverse Order Of String By Preserving Space Position

package com.softwaretestingo.interviewprograms;
import java.util.ArrayList;
import java.util.List;
public class InterviewPrograms8 
{
	/*
	 * Input:  Today is January 5th 
	 * Output: 5thja nu aryisTo day
	 */
	public static void main(String[] args) 
	{
		String input = "Today is January 5th";
		String[] output = input.split(" ");
		StringBuffer sb = new StringBuffer();
		List<Integer> spaceIndex = new ArrayList<>();
		for (int i=0; i<output.length-1; i++ ) 
		{
			spaceIndex.add(input.indexOf(" ")+i);
			input=input.replaceFirst(" ","");
		}
		for ( int i=output.length-1; i>=0 ;i--)
		{
			sb.append(output[i]);
		}
		for ( int i : spaceIndex ) 
			sb.insert(i," ");
		System.out.println(sb);
	}
}

Output:

5thJa nu aryisTo day

Explanation:

Here’s a step-by-step explanation of the program:

  • The class InterviewPrograms8 is declared as public. The name of the class should ideally be in camel case format, like InterviewPrograms. The class contains the main method, where the program execution starts.
  • There’s a comment that explains the input and expected output of the program. The input string is “Today is January 5th”, and the expected output is “5th January is Today”, where the order of words is reversed.
  • The program imports the ArrayList and List classes from the java.util package. These classes are used for list manipulation.
  • The main method is declared with the public and static modifiers. It takes an array of strings named args as a parameter. This array is used to pass command-line arguments to the program, although in this case, it is not utilized.
  • Inside the main method, a string variable input is declared and initialized with the input string “Today is January 5th”.
  • The input string is split into an array of words using the space delimiter ” ” and stored in the output array.
  • A StringBuffer named sb is created to store the reversed string.
  • A List of integers named spaceIndex is created to keep track of the positions of spaces in the original input string.
  • A for loop is used to iterate over each word in the output array, except the last word. The loop variable i starts from 0 and goes up to the length of output minus 1.
  • Inside the loop, the index of the space character ” ” is retrieved using the indexOf method of the input string. The index is adjusted by adding i to account for spaces that have been removed from the input string.
  • The spaceIndex list is updated by adding the adjusted index.
  • The input string is modified by replacing the first occurrence of a space ” ” with an empty string “”, effectively removing the space.
  • After processing all words except the last one, another for loop is used to iterate over the output array in reverse order. The loop variable i starts from the last index (output.length-1) and decrements.
  • Inside the loop, each word is appended to the sb string using the append method of the StringBuffer.
  • A final for loop is used to iterate over the spaceIndex list. For each index i, a space character ” ” is inserted at the corresponding position in the sb string using the insert method.
  • Finally, the program prints the sb string, which represents the reversed string with preserved spaces, to the console as the output.

That’s the step-by-step explanation of the given Java program. If you have any specific questions or need further clarification, feel free to ask!

Alternative Way 1:

This Java program takes an input string “he is a good boy”, reverses the characters of the whole string while keeping the words intact, and then prints the reversed string as the output. The program demonstrates string splitting, string reversal using StringBuilder, and inserting spaces to reconstruct the reversed string with the original word order.

package com.softwaretestingo.interviewprograms;
import java.util.Arrays;
public class InterviewPrograms16 
{
	/*
	 * Input : he is a good boy 
	 * Output: yo bd o ogas ieh
	 */
	public static void main(String[] args) 
	{
		String input="he is a good boy";
		String[] split=input.split(" ");
		
		StringBuilder sb=new StringBuilder(input.replaceAll(" ", ""));
		sb.reverse();
		
		int count=0;
		for(String o:Arrays.asList(split).subList(0, split.length-1))
		{
			count=count+o.length();
			sb.insert(count, " ");
			count++;
		}
		System.out.println(sb);
	}
}

Output:

yo bd o ogas ieh

Explanation of the program section by section:

  • The program defines a class named InterviewPrograms16.
  • Inside the class, there is a main method, which serves as the entry point for the program.
  • The input string “he is a good boy” is initialized as input.
  • The program splits the input string into an array of strings using the split method, with the delimiter ” ” (space), and stores the result in the string array split. This step separates the words of the input string.
  • A StringBuilder named sb is created, containing the entire input string with spaces removed (using replaceAll(” “, “”)), resulting in “heisagoodboy”.
  • The reverse method is called on the sb StringBuilder object to reverse the entire string. After this step, sb will contain “yobdoogasihe”.
  • The program initializes an integer variable count to keep track of the position where spaces should be inserted in the reversed string.
  • The program uses an enhanced for loop to iterate through the list of words (excluding the last word) obtained from Arrays.asList(split).subList(0, split.length-1).
  • In each iteration, the length of the current word is added to count.
  • A space character is inserted at the position count using the insert method of the StringBuilder.
  • The count is incremented by 1 to account for the space inserted.
  • Finally, the reversed string with the original word order is printed using System.out.println

In summary, this program takes an input string, reverses its characters while preserving the word order, and prints the reversed string. It showcases string manipulation using StringBuilder, string splitting, and the use of a loop to insert spaces at appropriate positions to reconstruct the reversed string with the original word order. The output will be “yo bd o ogas ieh” for the input “he is a good boy”.

Alternative Way 2:

This Java program takes an input string “he is a good boy”, reverses the characters of each word while preserving the word order, and then prints the reversed string as the output. The program demonstrates string manipulation, the use of ArrayList to store word lengths, iteration through the string, and concatenation to reconstruct the reversed string with the original word order.

package com.softwaretestingo.interviewprograms;
import java.util.ArrayList;
import java.util.Scanner;
public class InterviewPrograms16_1 
{
	/*
	 * Input : he is a good boy 
	 * Output: yo bd o ogas ieh
	 */
	public static void main(String[] args) 
	{
		String a = " he is a good boy " ;
		// Output : yo bd o ogas ieh
		String a1 = " " ;
		String result = " " ;
		int k = 1 ;
		ArrayList < Integer > lenArrayList = new ArrayList < > ( ) ;
		Scanner scanner = new Scanner ( a ) ;
		while ( scanner.hasNext ( ) )
		{
			String word = scanner.next ( ) ;
			a1 = a1 + word ;
			lenArrayList.add(word.length());
		}

		for ( int i = 0 ; i <= lenArrayList.size ( ) - 1 ; i ++ )
		{
			for ( int j = 0 ; j <=lenArrayList.get( i ) -1 ; j ++ )
			{
				result= result + a1.charAt(a1.length ( ) - k ) ;
				k ++ ;
			}
			result = result + " " ;
		}
		System.out.println(result);
	}
}

Output:

yo bd o ogas ieh

Explanation of the program section by section:

  • The program defines a class named InterviewPrograms16_1.
  • Inside the class, there is a main method, which serves as the entry point for the program.
  • The input string ” he is a good boy ” is initialized as a.
  • An empty string a1 is initialized to store the words extracted from the input string.
  • An empty string result is initialized to store the reversed string.
  • An integer k is initialized with the value 1, to keep track of the character position during word reversal.
  • An ArrayList named lenArrayList is created to store the lengths of each word.
  • The program uses a Scanner to process the input string a and extract each word.
  • During each iteration, the current word is appended to a1, and its length is added to the lenArrayList.
  • The program uses a nested for loop to iterate through each word in lenArrayList.
  • In the outer loop, i represents the index of the word in lenArrayList.
  • In the inner loop, j represents the character index within the current word.
  • During each iteration, the characters of the words are appended to the result string in reverse order, using a1.charAt(a1.length() – k).
  • The variable k is incremented for each character added to the result.
  • After reversing each word, a space is added to result to separate the reversed words.
  • Finally, the reversed string with the original word order is printed using System.out.println.

In summary, this program takes an input string, extracts each word, reverses the characters of each word, and then prints the reversed string with the original word order. It showcases string manipulation, the use of ArrayList to store word lengths, the use of a Scanner to process input, and nested loops to achieve the desired result. The output will be “yo bd o ogas ieh” for the input “he is a good boy”.

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