Open In App

URLify a given string (Replace spaces with %20)

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
34 Likes
Like
Report

Given a string s, the task is to replace all the spaces in the string with '%20'.

Examples: 

Input: s = "i love programming"
Output: "i%20love%20programming"
Explanation: The 2 spaces are replaced by '%20'

Input: s = "ab cd"
Output: "ab%20cd"

Approach:

The idea is to iterate through each character of the input string and create a new string by replacing space characters with the '%20' escape sequence.

Step by step approach:

  1. Iterate through each character in the input string from start to end.
  2. Check if the current character is a space.
    • If a space is found, append '%20' to the result string.
    • If the current character is not a space, append the original character to the result string.
  3. Return the final modified string with spaces replaced by '%20'.
C++
Java Python C# JavaScript

Output
i%20love%20programming

Time Complexity: O(n), as the string is traversed only once.
Auxiliary Space: O(n), used for output string.


Next Article
Article Tags :

Similar Reads