I am preparing for an interview and I have been looking at practice coding problems and I had a few questions about the solutions for the code.
The problem was: write a method to replace all spaces in a string with '%20'. You can assume that the string has enough space at the end to hold extra characters and that you are given the real length of the string. Example:
input: "My dog ", 6
output: "My%20dog"
Solution:
void replaceSpaces(char[]str, int length){
int spaceCount = 0, newLength, i;
for(i = 0; i <length; i++){
if(str[i] == ' '){
spaceCount++;
}
}
newLength = length + spaceCount * 2;
str[newLength]= '/0';
for(i= length -1; i>=0; i--){
if(str[i] == ' '){
str[newLength - 1] = '0';
str[newLength - 2] = '2';
str[newLength - 3] = '%';
newLength = newLength - 3;
}else{
str[newLength -1] = str[i];
newLength = newLength - 1;
}
}
}
First question with this code are how would I implement this in the main class? I wanted to get a better idea of how exactly the char array works and see if I can test this code.
Secondly, what does this line mean and what is its purpose? I tried to look up what '/0' means in java but could find nothing:
str[newLength] = '/0';
Thirdly why do we need to subtract 3 from the newLength in the second half of the code where we are adding in space for the %20? This is the line below:
newLength = newLength - 3;
Stringrather thanchar[]?String newString = new String(str).replaceAll(" ", "%20");?