forked from mandliya/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1-3-URLify.cpp
47 lines (42 loc) · 1.22 KB
/
1-3-URLify.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
* Cracking the coding interview Edition 6
* Problem 1.3 URLify --> Replace all the spaces in a string with '%20'.
* Assumption : We have enough space to accommodate addition chars
* Preferebly in place
*/
#include <iostream>
#include <cstring>
/*
* Function : urlify
* Args : string long enough to accommodate extra chars + true len
* Return : void (in place transformation of string)
*/
void urlify(char *str, int len)
{
int numOfSpaces = 0;
int i = 0, j = 0;
for ( i = 0; i < len; ++i ) {
if (str[i] == ' ') {
++numOfSpaces;
}
}
int extendedLen = len + 2 * numOfSpaces;
i = extendedLen - 1;
for( j = len - 1; j >= 0; --j ) {
if ( str[j] != ' ' ) {
str[i--] = str[j];
} else {
str[i--] = '0';
str[i--] = '2';
str[i--] = '%';
}
}
}
int main()
{
char str[] = "Mr John Smith "; //String with extended length ( true length + 2* spaces)
std::cout << "Actual string : " << str << std::endl;
urlify(str, 13); //Length of "Mr John Smith" = 13
std::cout << "URLified string : " << str << std::endl;
return 0;
}