Be the first user to complete this post

  • 0
Add to List
Medium

24. Replace Spaces with '%20' Without Using Default Functions

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 the true length of a string
Output: Updated string in which each space is replaced by the '%20'

Example:

Input: This is tutorial horizon
Output: this%20is%20tutorial%20horizon

Approach:

  • 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 %,20.
  • If you encounter the character, copy it

Output:

  Input String : This is tutorial horizon
Output String : This%20is%20tutorial%20horizon