Coding Challenge Day-4: Problem 2: Replace all spaces in a string with ‘%20’

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

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

Problem: Write a method to replace all spaces in a string with ‘%20’. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the “true” length of the string. (Note: if implementating in JAVA, please use a character array so that you can perform this operation in place.)

Sample input: “Believe in yourself “
Output: New String: Believe%20in%20yourself

Sample input: “Tech n Art “
Output: New String: Tech%20n%20Art

Sample input: “Now or never “
Output: New String: Now%20or%20never

Solution:

  • Start with initializing a string and then converting into character array (sufficient space at the end of the string to hold the additional characters)
  • pass the array and the ‘true’ length of the string
  • in the method start with finding the number of spaces in array
  • find the new length (orgininal_length +2*no_of_spaces)
  • run the second loop from the end of the array and replace all the spaces with ‘%20’
package string;

public class Program004replace_with_percent {
	
	public static void replace (char c[], int length){
		int spaces=0;
		for(int i=0; i<length; i++){
			if(c[i]==' ')
				spaces++;
		}
		
		int new_length= length + spaces*2;
		int n=0;
		
		for (int i= length-1; i>=0; i--){
	
			if(c[i]==' '){
				c[new_length-n-1]='0';
				c[new_length-n-2]='2';
				c[new_length-n-3]='%';
				n+=3;
			}
			
			else{
				c[new_length-n-1]= c[i];
				n++;
			}		
		}
		
		System.out.print("New String: "  );
		for(int i=0; i<new_length; i++){
			System.out.print(c[i]);
		}
	}
	
	public static void main (String [] args){
		String str= "Now or never    ";
		char c[]= str.toCharArray();
		replace(c,12);
		
		
	}

}

Download Code

References:
1) Cracking the coding interview (by Gayle Laakmann McDowell)

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: