-
Notifications
You must be signed in to change notification settings - Fork 0
/
offer-05-ReplaceSpaces.c
96 lines (86 loc) · 1.44 KB
/
offer-05-ReplaceSpaces.c
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <stdio.h>
#include <stdlib.h>
#include "minunit.h"
// malloc new space to store retval
char *replaceSpace(char *s)
{
if (s == NULL)
{
return NULL;
}
int count = 0;
for (int i = 0; s[i] != '\0'; i++)
{
count++;
}
char *retVal = (char *)malloc((3 * count + 1) * sizeof(char));
int index = 0;
for (int i = 0; s[i] != '\0'; i++)
{
if (s[i] == ' ')
{
retVal[index++] = '%';
retVal[index++] = '2';
retVal[index++] = '0';
}
else
{
retVal[index++] = s[i];
}
}
retVal[index] = '\0';
return retVal;
}
char *replaceSpace2(char *s)
{
if (s == NULL)
{
return NULL;
}
int count = 0, whiteSpace = 0;
for (int i = 0; s[i] != '\0'; i++)
{
count++;
if (s[i] == ' ')
{
whiteSpace++;
}
}
if (whiteSpace == 0)
{
return s;
}
s = (char *)realloc(s, sizeof(char) * (count + 2 * whiteSpace + 1));
s[count + 2 * whiteSpace] = '\0'; // end
int index = count + 2 * whiteSpace - 1;
for (int i = count - 1; i >= 0; i--)
{
if (s[i] == ' ')
{
s[index--] = '0';
s[index--] = '2';
s[index--] = '%';
}
else
{
s[index--] = s[i];
}
}
return s;
}
MU_TEST(test_case)
{
// 输入:s = "We are happy." 输出:
// "We%20are%20happy."
mu_check(5 == 7);
}
MU_TEST_SUITE(test_suite)
{
MU_RUN_TEST(test_case);
}
int main()
{
MU_RUN_SUITE(test_suite);
MU_REPORT();
return MU_EXIT_CODE;
}