# Method to replace all spaces in a String with '%20'

Problem statement (extracted from cracking the coding interview):

Write a method to replace all spaces in a string with'%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place.)

EXAMPLE Input: "Mr John Smith

Output: "Mr%20Dohn%20Smith"

My Solution:

public class InterviewMain {

public static void main(String[] args){

//Q 1.4
String str = "Example String with spaces           ";
replaceSpaces(str);
}

public static void replaceSpaces(String str){

int trueLength = getTrueLength(str);

char[] strChar = str.toCharArray();
int spaceCount = 0;
int finalLength;

//count the number of spaces in the original string
for (int i=0; i<trueLength; i++){
if (strChar[i]== ' ')spaceCount++;
}

//get the length of final char array
finalLength = trueLength + spaceCount*2;
char[] finalArr = new char[finalLength];

//update final array here
int spaces = 0;
char temp;
int index;

for (int i=0; i < trueLength; i++){
temp = strChar[i];

if (temp==' '){
finalArr[getInsertIndex(i,spaces)]= '%';
finalArr[getInsertIndex(i+1,spaces)] = '2';
finalArr[getInsertIndex(i+2,spaces)] = '0';
spaces++;
continue;
}

index = getInsertIndex(i,spaces);
finalArr[index] = temp;
}

//print results here
for (int i=0; i < finalLength; i++){
System.out.print(finalArr[i]);
}
}

private static int getTrueLength(String str) {
int count=0;
int length = str.length();
char[] strChar = str.toCharArray();

//backtrack from end of string to count padding
for (int i=length-1; i >=0; i--){
if (strChar[i]!= ' ')break;
count++;
}
return length-count;
}

private static int getInsertIndex(int i, int spaces){
return (i + spaces*2);
}
}


I was wondering if someone could review this and point out what I have done right and where I can improve upon. Thank you

• – Caridorc Mar 5 '16 at 10:28

It's important to pay attention to every bit of detail in the problem description:

Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place.)

As you're implementing this in Java, your method should receive a char[] instead of a String. And if I interpret correctly, the "true" length is the length without the padding, and is an additional parameter, giving the signature:

void replaceSpaces(char[] input, int trueLength) { ... }


With this established, the implementation can be simplified:

• No need for getTrueLength: it's a given
• No need for calculating the final size, it's given by input.length
• As @rolfl pointed out, the size of input is not 100% clear. The description only states that it has sufficient space. So indeed, we may need to calculate the final size.
• The printing is unnecessary and should be removed, as it breaks the single responsibility of the method

Another improvement in the implementation is that you don't need to count the spaces. You can walk backward, tracking two positions in parallel:

• The last position to write to (starts at input.length - 1)
• The last position in the text (starts at trueLength - 1)

Walk backward as long as the text position is smaller than the end position. If you see a space, overwrite the the values at the position with %20. Otherwise simply copy the input.

void replaceSpaces(char[] input, int trueLength) {
//int end = input.length - 1;
int end = trueLength + (countSpaces(input, trueLength) * 2) - 1;
for (int textEnd = trueLength - 1; textEnd < end; textEnd--) {
if (input[textEnd] == ' ') {
input[end--] = '0';
input[end--] = '2';
input[end--] = '%';
} else {
input[end--] = input[textEnd];
}
}
}

• Nice, but you are assuming that the input char[] is the exact length required to store the result. The specification suggests it "... has sufficient space ....". You really need to count the spaces first before walking back and replacing them because you need to compute the final length. – rolfl Mar 5 '16 at 11:46
• Well-spotted, amended my answer – janos Mar 5 '16 at 11:55
• Wouldn't a for loop be cleaner? for (int textEnd = trueLength - 1; textEnd < end; textEnd-- – Caridorc Mar 5 '16 at 12:18
• You're right @Caridorc, amended it – janos Mar 5 '16 at 12:37