题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
#include<iostream>
using namespace std;
class Solution{
public :
void replaceSpace(char *str,int length)
{
int i = 0;
int NumOfSpace = 0;
while(i<length)
{
if (str[i]==' ')
NumOfSpace++;
i++;
}
int OldLen = i;
int NewLen = OldLen + 2*NumOfSpace;
while( OldLen>=0 && NewLen>OldLen)
{
if (str[OldLen]==' ')
{
str[NewLen--]='0';
str[NewLen--]='2';
str[NewLen--]='%';
}
else {
str[NewLen--]=str[OldLen];
}
OldLen--;
}
}
};
int main()
{
Solution solution;
char str[] ="hello world";
cout<<str<<endl;
solution.replaceSpace(str,11);
cout<<str<<endl;
}