实现一个函数,将一个字符串中的空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
#include<iostream>
#include<string>
using namespace std;
void replaceSpace(char *str,int length) {
int oldlen=strlen(str);
int sum=0;
int newlen;
for(int i=0;i<oldlen;i++){
if(str[i]==' ')
sum++;
}
newlen=oldlen+sum*2;
int p1=oldlen;
int p2=newlen;
str[newlen]='\0';
while(p1>0&&p2>0){
if(str[p1]==' '){
str[p2]='0';
str[p2-1]='2';
str[p2-2]='%';
p1--;
p2=p2-3;
}
else
str[p2--]=str[p1--];
}
cout<<str<<endl;
}
void main()
{
char a[100]="I love u";
replaceSpace(a,100);
while(1);
}
思路:从后往前,指针移动。