描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路和代码
主要分为三步:
- 扫描一遍字符串,得到字符串长度和空格的个数
- 由空格的个数计算出新的字符串的长度
- 从后往前复制
class Solution {
public:
void replaceSpace(char *str,int length) {
if(str == nullptr || length <= 0)
return ;
//第一次遍历,求出空格的个数
int originalLength = 0;
int numberOfBlank = 0;
for(int i=0; str[i]!='\0'; i++){
if(str[i] == ' ')
++numberOfBlank;
++originalLength;
}
//计算新长度
int newLength = originalLength + numberOfBlank * 2;
if(newLength > length)
return ;
//从后往前复制
int p1 = originalLength;
int p2 = newLength;
while(p1 >= 0 && p2 > p1){
if(str[p1] == ' '){
str[p2--] = '0';
str[p2--] = '2';
str[p2--] = '%';
}
else
str[p2--] = str[p1];
p1--;
}
}
};