Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Replace all spaces in a String with ‘%20′

Objec­tive: Write an algo­rithm to replace all spaces in a given string with ‘%20′. You can con­sider 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

Out­put: Updated string in which each space is replaced by the ‘%20′

Example: 

Input String : I am Sumit Jain    

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

Approach:

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

Com­plete Code:

Out­put:

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

You may also like...