请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
有三种思路:
1. 从前向后,遇到空格,则把后面左右字符向后移动两个位置,移动次数较多
2. 从前向后遍历一次,计算空格个数count,新申请strlen + 2*count 大小的内存,从前向后遍历赋值,最后copy回原str
3. 从前向后遍历一次,计算空格个数count,从strlen + 2*count的位置开始向前,依次赋值(最后一个字符为‘\0’)
代码如下:
class Solution {
public:
//方法1:从前向后 遇到空格则把后面的字符都向后移动2个位置
//方法2:申请一块新的内存 从前向后遇到空格则替换
void replace_spaces_by_memory(char *str,int length){
//可以先从前向后遍历一次计算空格的个数 下面这里偷懒了
char* newstr = (char*)malloc(length*3 + 1);
int index = 0;
for(int i = 0; i < length; i++)
{
if(str[i] == ' ')
{
newstr[index++] = '%';
newstr[index++] = '2';
newstr[index++] = '0';
}
else
{
newstr[index++] = str[i];
}
}
newstr[index] = '\0';
memcpy(str, newstr, index);
free(newstr);
}
//方法3:从前向后计算空格数量 从后向前移动替换
void replace_space_by_move(char* str, int length){
int count = 0;
for(int i = 0; i < length; i++){
if(str[i] == ' '){
count++;
}
}
int strIndex = length;
int newIndex = length + 2*count; //每出现一个空格 则比原有字符串多出两个字符
while(strIndex >= 0)
{
if(str[strIndex] == ' '){
str[newIndex--] = '0';
str[newIndex--] = '2';
str[newIndex--] = '%';
strIndex--;
}
else{
str[newIndex--] = str[strIndex--];
}
}
}
void replaceSpace(char *str,int length) {
replace_spaces_by_memory(str, length);
//replace_space_by_move(str, length);
}
};