Replace all spaces in a String with ‘%20’

Objective: Write an algorithm to replace all spaces in a given string with ‘%20’. You can consider that string has enough space at the end of the string to hold the extra characters.

Input: A String and true length of a string

Output: Updated string in which each space is replaced by the ‘%20’


Input String : I am Sumit Jain    

Output String : I%20am%20Sumit%20Jain


  • Count the total spaces in a string in one iteration, say the count is spaceCount
  • Calculate the new length of a string by newLength = length + 2*spaceCount; (we need two more places for each space since %20 has 3 characters, one character will occupy the blank space and for rest two we need extra space)
  • Do another iteration in reverse direction
  • If you encounter the space, for next 3 spaces put %,2,0.
  • If you encounter the character, copy it

Complete Code:


Input String : I am Sumit Jain
Output String : I%20am%20Sumit%20Jain

Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.

You may also like...

%d bloggers like this: