Open In App
Related Articles

URLify a given string (Replace spaces with %20)

Improve Article
Improve
Save Article
Save
Like Article
Like

 Write a method to replace all the spaces in a string with ‘%20’. You may assume that the string has sufficient space at the end to hold the additional characters and that you are given the “true” length of the string.
Examples: 

Input: "Mr John Smith", 13
Output: Mr%20John%20Smith

Input: "Mr John Smith   ", 13
Output: Mr%20John%20Smith

A simple solution is to create an auxiliary string and copy characters one by one. Whenever space is encountered, place %20 in place of it.

Approach 1: using string.replace() function :

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
void replaceSpaces(string input)
{
    string rep = "%20";
    for(int i=0 ; i<input.length() ; i++)
    {
        if(input[i] == ' ')
            input.replace(i,1,rep);
    }
    cout<<input;
}
 
int main()
{
    string input = "Mr John Smith";
    replaceSpaces(input);
 
    return 0;
}


Java




/*package whatever //do not write package name here */
import java.io.*;
 
class GFG {
  public static void replaceSpaces(String input)
  {
    String rep = "%20";
    for (int i = 0; i < input.length(); i++) {
      if (input.charAt(i) == ' ') {
        StringBuilder string
          = new StringBuilder(input);
        string.setCharAt(i, rep);
      }
    }
    System.out.println(input);
  }
  public static void main(String[] args)
  {
    System.out.println("GFG!");
    String input = "Mr John Smith";
    replaceSpaces(input);
  }
}
 
// This code is contributed by Susobhan Akhuli


Python3




#Python code for the same approach
def replaceSpaces(input):
    rep = "%20"
    for i in range(len(input)):
        if(input[i] == ' '):
            input = input.replace(input[i],rep)
    print(input)
 
# driver code
input = "Mr John Smith"
replaceSpaces(input)
 
# This code is contributed by shinjanpatra


Javascript




<script>
 
// JavaScript code for the approach
function replaceSpaces(input)
{
    let rep = "%20"
    for(let i=0 ; i<input.length ; i++)
    {
        if(input[i] == ' ')
            input = input.replace(input[i],rep);
    }
    document.write(input);
}
 
// driver code
let input = "Mr John Smith"
replaceSpaces(input)
 
// This code is contributed by shinjanpatra
 
</script>


C#




// C# implementation of above approach
using System;
     
class GFG
{
    public static void Main()
    {
        // Instantiate the string
        String str = "Mr John Smith ";
         
        // Trim the given string
        str = str.Trim();
         
          for (int i = 0; i < str.Length; i++)
            if (str[i] == ' ')
                str = str.Replace(" ", "%20");
         
        // Display the result
        Console.Write(str);
    }
}
 
// This code is contributed by Susobhan Akhuli


Output

Mr%20John%20Smith

Time complexity: O(N2) where N is the length of the string. because it is using replace method inside for loop
Auxiliary space: O(1). 

Approach 2: A better solution to do in-place assuming that we have extra space in the input string. We first count the number of spaces in the input string. Using this count, we can find the length of the modified (or result) string. After computing the new length we fill the string in-place from the end. 

Below is the implementation of the above approach:

C++




// C++ program to replace spaces with %20
#include<stdio.h>
 
// Maximum length of string after modifications.
const int MAX = 1000;
 
// Replaces spaces with %20 in-place and returns
// new length of modified string. It returns -1
// if modified string cannot be stored in str[]
int replaceSpaces(char str[])
{
    // count spaces and find current length
    int space_count = 0, i;
    for (i = 0; str[i]; i++)
        if (str[i] == ' ')
            space_count++;
 
    // Remove trailing spaces
    while (str[i-1] == ' ')
    {
       space_count--;
       i--;
    }
 
    // Find new length.
    int new_length = i + space_count * 2 + 1;
 
    // New length must be smaller than length
    // of string provided.
    if (new_length > MAX)
        return -1;
 
    // Start filling character from end
    int index = new_length - 1;
 
    // Fill string termination.
    str[index--] = '\0';
 
    // Fill rest of the string from end
    for (int j=i-1; j>=0; j--)
    {
        // inserts %20 in place of space
        if (str[j] == ' ')
        {
            str[index] = '0';
            str[index - 1] = '2';
            str[index - 2] = '%';
            index = index - 3;
        }
        else
        {
            str[index] = str[j];
            index--;
        }
    }
 
    return new_length;
}
 
// Driver code
int main()
{
    char str[MAX] = "Mr John Smith   ";
 
    // Prints the replaced string
    int new_length = replaceSpaces(str);
    for (int i=0; i<new_length; i++)
        printf("%c", str[i]);
    return 0;
}


Java




// Java program to replace spaces with %20
class GFG
{
 
    // Maximum length of string
    // after modifications.
    static int MAX = 1000;
 
    // Replaces spaces with %20 in-place
    // and returns new length of modified string.
    // It returns -1 if modified string
    // cannot be stored in str[]
    static char[] replaceSpaces(char[] str)
    {
 
        // count spaces and find current length
        int space_count = 0, i = 0;
        for (i = 0; i < str.length; i++)
            if (str[i] == ' ')
                space_count++;
 
        // count spaces and find current length
        while (str[i - 1] == ' ')
        {
            space_count--;
            i--;
        }
 
        // Find new length.
        int new_length = i + space_count * 2;
 
        // New length must be smaller than length
        // of string provided.
        if (new_length > MAX)
            return str;
 
        // Start filling character from end
        int index = new_length - 1;
 
        char[] old_str = str;
        str = new char[new_length];
 
        // Fill rest of the string from end
        for (int j = i - 1; j >= 0; j--)
        {
 
            // inserts %20 in place of space
            if (old_str[j] == ' ')
            {
                str[index] = '0';
                str[index - 1] = '2';
                str[index - 2] = '%';
                index = index - 3;
            }
             
            else
            {
                str[index] = old_str[j];
                index--;
            }
        }
        return str;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        char[] str = "Mr John Smith ".toCharArray();
 
        // Prints the replaced string
        str = replaceSpaces(str);
 
        for (int i = 0; i < str.length; i++)
            System.out.print(str[i]);
    }
}
 
// This code is contributed by
// sanjeev2552


Python3




# Maximum length of string after modifications.
MAX = 1000;
 
# Replaces spaces with %20 in-place and returns
# new length of modified string. It returns -1
# if modified string cannot be stored in str[]
def replaceSpaces(string):
     
    # Remove remove leading and trailing spaces
    string = string.strip()
 
    i = len(string)
 
    # count spaces and find current length
    space_count = string.count(' ')
 
    # Find new length.
    new_length = i + space_count * 2
 
    # New length must be smaller than length
    # of string provided.
    if new_length > MAX:
        return -1
 
    # Start filling character from end
    index = new_length - 1
 
    string = list(string)
 
    # Fill string array
    for f in range(i - 2, new_length - 2):
        string.append('0')
 
    # Fill rest of the string from end
    for j in range(i - 1, 0, -1):
 
        # inserts %20 in place of space
        if string[j] == ' ':
            string[index] = '0'
            string[index - 1] = '2'
            string[index - 2] = '%'
            index = index - 3
        else:
            string[index] = string[j]
            index -= 1
 
    return ''.join(string)
 
# Driver Code
if __name__ == '__main__':
    s = "Mr John Smith "
    s = replaceSpaces(s)
    print(s)
 
# This code is contributed by Vinayak


C#




// C# program to replace spaces with %20
using System;
 
class GFG
{
 
    // Maximum length of string
    // after modifications.
    static int MAX = 1000;
 
    // Replaces spaces with %20 in-place
    // and returns new length of modified string.
    // It returns -1 if modified string
    // cannot be stored in []str
    static char[] replaceSpaces(char[] str)
    {
 
        // count spaces and find current length
        int space_count = 0, i = 0;
        for (i = 0; i < str.Length; i++)
            if (str[i] == ' ')
                space_count++;
 
        // count spaces and find current length
        while (str[i - 1] == ' ')
        {
            space_count--;
            i--;
        }
 
        // Find new length.
        int new_length = i + space_count * 2;
 
        // New length must be smaller than
        // length of string provided.
        if (new_length > MAX)
            return str;
 
        // Start filling character from end
        int index = new_length - 1;
 
        char[] new_str = str;
        str = new char[new_length];
 
        // Fill rest of the string from end
        for (int j = i - 1; j >= 0; j--)
        {
 
            // inserts %20 in place of space
            if (new_str[j] == ' ')
            {
                str[index] = '0';
                str[index - 1] = '2';
                str[index - 2] = '%';
                index = index - 3;
            }
            else
            {
                str[index] = new_str[j];
                index--;
            }
        }
        return str;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        char[] str = "Mr John Smith ".ToCharArray();
 
        // Prints the replaced string
        str = replaceSpaces(str);
 
        for (int i = 0; i < str.Length; i++)
            Console.Write(str[i]);
    }
}
 
// This code is contributed by 29AjayKumar


Javascript




// Javascript program to replace spaces with %20
 
// Maximum length of string after modifications.
const  MAX = 1000;
 
// Replaces spaces with %20 in-place and returns
// new length of modified string. It returns -1
// if modified string cannot be stored in str[]
function replaceSpaces( str)
{
    // count spaces and find current length
    let space_count = 0, i;
    for (i = 0; str[i]; i++)
        if (str[i] == ' ')
            space_count++;
 
    // Remove trailing spaces
    while (str[i-1] == ' ')
    {
       space_count--;
       i--;
    }
 
    // Find new length.
    let new_length = i + space_count * 2 + 1;
 
    // New length must be smaller than length
    // of string provided.
    if (new_length > MAX)
        return -1;
 
    // Start filling character from end
    let index = new_length - 1;
 
    // Fill string termination.
    str[index--] = '\0';
     
    let new_str="";
    // Fill rest of the string from end
    for (let j=i-1; j>=0; j--)
    {
        // inserts %20 in place of space
        if (str[j] == ' ')
        {
            new_str="%20"+new_str;
             
        }
        else
        {
            new_str=str[j]+new_str;
        }
    }
    console.log(new_str);
 
    return new_length;
}
 
// Driver code
let str = "Mr John Smith   ";
 
// Prints the replaced string
let new_length = replaceSpaces(str);
 
// This code is contributed by ratiagrawal.


Output: 

Mr%20John%20Smith

Time Complexity: O(n), where n is the true length of the string. 
Auxiliary Space: O(1), because the above program is an inplace algorithm.

Approach 3: Trim the string and call replaceAll() method, to replace all space Unicode to %20. 

Below is the implementation of the above approach:

C++




#include <iostream>
#include <string>
 
using namespace std;
 
int main()
{
 
  // Instantiate the string
  string str = "Mr John Smith   ";
 
  // Trim the given string
  str.erase(str.find_last_not_of(" \n\r\t")+1);
 
  // Replace All space (unicode is \\s) to %20
  size_t pos = str.find(" ");
  while (pos != string::npos)
  {
    str.replace(pos, 1, "%20");
    pos = str.find(" ", pos + 3);
  }
 
  // Display the result
  cout << str << endl;
 
  return 0;
}
 
// This code is contributed by factworx412


Java




// Java implementation of above approach
class GFG
{
    public static void main(String[] args)
    {
        // Instantiate the string
        String str = "Mr John Smith   ";
         
        // Trim the given string
        str = str.trim();
         
        // Replace All space (unicode is \\s) to %20
        str = str.replaceAll("\\s", "%20");
         
        // Display the result
        System.out.println(str);
    }
}


Python3




# Python3 implementation of above approach
 
# Instantiate the string
s = "Mr John Smith "
 
# Trim the given string
s = s.strip()
 
# Replace All space (unicode is \\s) to %20
s = s.replace(' ', "%20")
 
# Display the result
print(s)
 
# This code is contributed by vinayak


C#




// C# implementation of above approach
using System;
     
class GFG
{
    public static void Main()
    {
        // Instantiate the string
        String str = "Mr John Smith   ";
          
        // Trim the given string
        str = str.Trim();
          
        // Replace All space (unicode is \\s) to %20
        str = str.Replace(" ", "%20");
          
        // Display the result
        Console.Write(str);
    }
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
 
      // JavaScript implementation of above approach
       
      // Instantiate the string
      var str = "Mr John Smith ";
     / we can use regular expression for checking empty space /
      str = str.replace(/ /g,"%20")
 
      // Display the result
      document.write(str);
       
</script>


Output

Mr%20John%20Smith

Time complexity: O(N) where N is the length of the string.
Auxiliary space: O(1). 

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.


Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Last Updated : 17 Mar, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials