剑指offer(替换空格)
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
void replaceSpace(char *str, int length)
{
//记录空格出现的个数,申请一个等长的数组,用来暂时存储原数组
int times = 0;
char sstr[length];
for (int i = 0; i < length; ++i)
{
sstr[i] = str[i];
if (str[i] == ' ')
{
times++;
}
}
//数组扩容
int len = length + (times * 2);
str = (char *)realloc(str, sizeof(char) * len);
//寻找插入位置
int p = 0;
int q = 0;
while (p < length)
{
if (sstr[p] != ' ')
{
str[q] = sstr[p];
++p;
++q;
}
else
{
str[q++] = '%';
str[q++] = '2';
str[q++] = '0';
p++;
}
}
}