I’ve encountered this interview question and would like some help in trying to understand its solution:
Write a method to replace all spaces in a string with ‘%20’.
Solution (from a forum) :
char str[]="helo b";
int length = strlen(str);
int spaceCount = 0, newLength, i = 0;
for (i = 0; i < length; i++) {
if (str[i] == ' ') {
spaceCount++; //count spaces...
}
}
newLength = length + spaceCount * 2; //need space for 2 more characters..
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;
}
}
This program does not work for me…i would first like to understand the algorithm before diving into the code.
That sample is broken.
Buffer overflow, One pointless scan of the string (strlen), Hard to read.