Replace all spaces in a String with ‘%20’

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 true length of a string

Output: 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 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 %,2,0.
  • If you encounter the character, copy it

Complete Code:

public class ReplaceAllSpaces {
public void replace(String s1, int length) {
char[] chars = s1.toCharArray();
int spaceCount = 0;
for (int i = 0; i < length; i++) {
if (chars[i] == ' ') {
spaceCount++;
}
}
int newLength = length + 2 * spaceCount;
char [] charsNew = new char [newLength];
for (int i = length 1; i >= 0; i) {
if (chars[i] == ' ') {
charsNew[newLength 1] = '0';
charsNew[newLength 2] = '2';
charsNew[newLength 3] = '%';
newLength = newLength 3;
} else {
// System.out.println(chars[i]);
charsNew[newLength 1] = chars[i];
newLength = newLength 1;
}
}
System.out.println("Output String : " + String.valueOf(charsNew));
}
public static void main(String args[]) {
String s1 = "I am Sumit Jain";
int trueLength = s1.length();
System.out.println("Input String : " + s1);
ReplaceAllSpaces r = new ReplaceAllSpaces();
r.replace(s1, trueLength);
}
}


Output:

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