-
Notifications
You must be signed in to change notification settings - Fork 0
/
1.4 Repalce Spaces.cpp
74 lines (67 loc) · 1.49 KB
/
1.4 Repalce Spaces.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <stdio.h>
void move_tail(char *first, int length)
{
if (length > 0)
{
for (int i = length - 1; i >= 0; --i)
{
first[i + 2] = first[i];
}
}
}
void replace_spaces_forward(char *string, int length)
{
for (int i = 0; i < length; ++i)
{
if (string[i] == ' ')
{
move_tail(string + i + 1, length - i - 1);
string[i] = '%';
string[i + 1] = '2';
string[i + 2] = '0';
i += 2;
length += 2;
}
}
// TODO: no effect?
// string[length] = '\0';
}
void replace_spaces_backward(char *string, int length)
{
int count_space = 0;
for (int i = 0; i < length; ++i)
{
if (string[i] == ' ')
{
++count_space;
}
}
int new_length = length + count_space * 2;
int dest = new_length;
// TODO: no effect?
// string[dest] = '\0';
--dest;
for (int i = length - 1; i >= 0; --i)
{
if (string[i] == ' ')
{
string[dest--] = '0';
string[dest--] = '2';
string[dest--] = '%';
}
else
{
string[dest--] = string[i];
}
}
}
int main(int argc, char const *argv[])
{
char string1[100] = "a test case ";
replace_spaces_forward(string1, 13);
printf("%s\n", string1);
char string2[100] = "a test case ";
replace_spaces_backward(string2, 13);
printf("%s\n", string2);
return 0;
}