1.3 - URLify
Write a method to replace all 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. EXAMPLE Input: "Mr John Smith ", 13 Output: "Mr%20John%20Smith"

Algorithm:

1
#include <stdio.h>
2
3
4
char* URLify(char* testStr, int len){
5
6
int countSpace = 0;
7
8
int i = 0;
9
while(testStr[i] != '\0'){
10
if( testStr[i] == ' '){
11
countSpace++;
12
}
13
i++;
14
}
15
16
int realLen = len + countSpace * 2;
17
testStr[realLen] = '\0';
18
19
for(int i = len - 1; i >= 0; i--){
20
if(testStr[i] == ' '){
21
testStr[realLen - 1] = '0';
22
testStr[realLen - 2] = '2';
23
testStr[realLen - 3] = '%';
24
realLen -= 3;
25
}else{
26
testStr[realLen - 1] = testStr[i];
27
realLen--;
28
}
29
}
30
return testStr;
31
}
Copied!

Test:

1
int main(){
2
3
//*** stack smashing detected ***: terminated
4
//char testStr1[6] = "ab cd";
5
char testStr1[100] = "ab cd";
6
printf("URLify = %s\n", URLify(testStr1, 6));
7
8
return 0;
9
}
Copied!
Copy link