Coding Challenge Day- 12: Problem 2: Reverse The String With Preserving The Position Of Spaces

Hello! So I’m doing a 30 day coding challenge where I solve a few questions every day and thought of posting them here on my blog so that you guys can join the challenge too!

Welcome to Coding challenge Day 12: Problem 2! Be sure to post your answers, queries etc in the comments!

Problem: Reverse The String With Preserving The Position Of Spaces

Sample input: Tech n Art
Output: Tech n Art—–> trAn h ceT

Sample input: Super who lock
Output: Super who lock—–> kcolo hwr epuS

Solution:

You can refer to this Link for detailed explanation!

package string;

public class Program011reverse_string_but_preserve_space_position {
	
	public static void reverse_string (String str){
		char [] c= str.toCharArray();
		int length = str.length();
		
		char [] reverse_str= new char[length];
		
		for(int i=0; i<length; i++){
			if(c[i]==' '){
				reverse_str[i]=' ';
			}
		}
		
		int j= length-1;
		
		for(int i=0; i<length; i++){
			if(c[i]!=' ')
			{
				if(reverse_str[j]==' ')
					j--;
			
			   
				   reverse_str[j]=c[i];
				    j--;
			     
				
			}
		
		}
		
		System.out.println(str+ "-----> " + String.valueOf(reverse_str));
		
	}
	
	public static void main (String [] args){
		String str="Super who lock";
		reverse_string(str);
	}

}

Download Code

Happy Learning!!

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: