0 题目
实现一个函数,将字符串中的 空格 替换为“%20”
1 分析
采用常规的从前向后的方式,那么后面的将移动很多次。
如果先计算出替换后字符串的总长度,然后从后向前开始替换,会效率很多。
void replaceSpace(char *str, int length)
{
int counts = 0;
char *str_tmp = str;
if (str == nullptr)
{
return;
}
// 计算需要替换的字符个数
while (*str_tmp != ‘\0‘)
{
if (*str_tmp == ‘ ‘)
{
++counts;
}
++str_tmp;
}
// 这里将空格替换为 %20,因此一个空格需要额外的两个空间来存储,因此每个空格扩容2个。
int index_new = length + counts * 2 - 1; // 新的尾下标
int index = length - 1; // 旧的
while (index >= 0)
{
if (str[index] == ‘ ‘) //需要替换的时候替换
{
str[index_new--] = ‘0‘;
str[index_new--] = ‘2‘;
str[index_new--] = ‘%‘;
}
else
{
str[index_new--] = str[index];//不需要替换的时候直接赋值
}
--index; // 向前移动
}
}