problem
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
code
class Solution {
public:
void replaceSpace(char *str,int length) {
int blackNum=0;
int old_length=0;
for(int i=0;str[i]!='\0';i++){
if(str[i]==' '){
blackNum++;
}
old_length++;
}
int new_length=old_length+2*blackNum;
if(new_length==old_length)
return;
int p1=old_length-1; int p2=new_length-1;
str[new_length]='\0';
while(p1>=0&&p2>=p1){
if(str[p1]==' '){
str[p2--]='0';
str[p2--]='2';
str[p2--]='%';
}else{
str[p2--]=str[p1];
p1--;
}
}
}
};
思路是遍历字符串,找到有多少空格,然后再计算新字符串的长度。我们从原字符串和新字符串最后一个字符开始逆向遍历,遇到老字符串的空格,相应的在新字符串上就用%20来代替。
参考文献
[1].题目:请实现一个函数,将一个字符串中的空格替换成“%20”.https://www.cnblogs.com/codingmengmeng/p/5857143.html