请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
来源:力扣(LeetCode)
新增扩容
char
* replaceSpace(char* s)
{
int len = strlen (s);
int cnt = 0;
// 统计字符串空格个数
for (int i = 0; i < len; i ++)
{
if (s[i] == ' ')
{
cnt ++;
}
}
// 申请扩容数组 '+ 1' 为 '\0'内存
char *ans = malloc (sizeof (int) * (len + cnt * 2 + 1));
for (int i = 0, j = 0; i < len; i ++, j ++)
{
if (s[i] == ' ')
{
ans[j] = '%';
ans[j + 1] = '2';
ans[j + 2] = '0';
j += 2;
}
else
{
ans[j] = s[i];
}
}
ans[len + cnt * 2] = '\0';
return ans;
}