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
#include <stdio.h>
#include <string.h>
#include <malloc.h>
// your refactored function
char* uri2hex(char *str)
{
int size = strlen(str) * 3;
char *out = (char*) malloc(size);
out[0] = '\0';
char cont[5];
cont[0] = '\0';
int i, start;
for(i = 0; i < strlen(str); i++)
{
if(str[i] == ':' && str[i + 1] == '/' && str[i + 2] == '/')
{
start = i + 2;
char *tmp = (char*) malloc(size);
strcpy(tmp, str);
tmp[start] = '\0';
strcat(out, tmp);
break;
}
}
for(i = start; i < strlen(str); i++)
{
if(str[i] != '/')
{
sprintf(cont,"%%%x", str[i]);
strcat(out, cont);
}
else
{
strcat(out, "/");
}
}
return out;
}
// my function (it don't need string.h)
char* uri2hex2(char *str, int len)
{
char *out = (char*) malloc(len * 3);
int i, start;
for (i = 0; i < len; i++)
{
if (str[i] == ':' && str[i + 1] == '/' && str[i + 2] == '/')
{
sprintf(out, "%s://", out);
start = i + 3;
break;
}
out[i] = str[i];
}
for (i = start; i < len; i++)
{
if (str[i] == '/')
{
sprintf(out, "%s/", out);
}
else
{
sprintf(out, "%s%%%x", out, str[i]);
}
}
return out;
}
int main()
{
char uri[] = "http://localhost/";
printf("%s", uri2hex2(uri, sizeof(uri) - 1));
return 0;
}