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"
Try it on GfG Practice
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:
- Iterate through each character in the input string from start to end.
- 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.
- Return the final modified string with spaces replaced by '%20'.
// C++ program to URLify a given string
#include <bits/stdc++.h>
using namespace std;
string URLify(string& s) {
int n = s.length();
string ans = "";
for (int i = 0; i<n; i++) {
// If " " is encountered,
// append "%20" to string
if (s[i] == ' ') {
ans.push_back('%');
ans.push_back('2');
ans.push_back('0');
}
// Else append the current
// character.
else {
ans.push_back(s[i]);
}
}
return ans;
}
int main() {
string s = "i love programming";
cout << URLify(s);
return 0;
}
import java.util.*;
public class Main {
public static String URLify(String s) {
int n = s.length();
StringBuilder ans = new StringBuilder();
for (int i = 0; i < n; i++) {
if (s.charAt(i) ==' ') {
ans.append("%");
ans.append("2");
ans.append("0");
} else {
ans.append(s.charAt(i));
}
}
return ans.toString();
}
public static void main(String[] args) {
String s = "i love programming";
System.out.println(URLify(s));
}
}
def urlify(s: str) -> str:
n = len(s)
# We use a list to mimic push_back behavior efficiently
ans = []
for i in range(n):
# If " " is encountered,
# append "%20" to the list
if s[i] == ' ':
ans.append('%')
ans.append('2')
ans.append('0')
# Else append the current
# character.
else:
ans.append(s[i])
# Join the list into a single string at the end
return "".join(ans)
if __name__ == "__main__":
s = "i love programming"
print(urlify(s))
using System;
using System.Collections.Generic;
public class Program
{
public static string Urlify(string s)
{
int n = s.Length;
List<char> ans = new List<char>();
for (int i = 0; i < n; i++)
{
if (s[i] == ' ')
{
ans.Add('%');
ans.Add('2');
ans.Add('0');
}
else
{
ans.Add(s[i]);
}
}
return new string(ans.ToArray());
}
public static void Main()
{
string s = "i love programming";
Console.WriteLine(Urlify(s));
}
}
const program = {
urlify: function(s) {
let n = s.length;
let ans = [];
for (let i = 0; i < n; i++) {
if (s[i] ===' ') {
ans.push('%');
ans.push('2');
ans.push('0');
} else {
ans.push(s[i]);
}
}
return ans.join('');
},
main: function() {
let s = 'i love programming';
console.log(this.urlify(s));
}
};
program.main();
Output
i%20love%20programming
Time Complexity: O(n), as the string is traversed only once.
Auxiliary Space: O(n), used for output string.