题目描述:
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
输入:
每个输入文件仅包含一组测试样例。
对于每组测试案例,输入一行代表要处理的字符串。
输出:
对应每个测试案例,出经过处理后的字符串。
样例输入:
We Are Happy
样例输出:
We%20Are%20Happy
#include<iostream>
#include<cmath>
#include<stack>
#include<vector>
#include<assert.h>
#include<algorithm>
using namespace std;
//替换空格为%20
class Solution {
public:
char* replaceSpace(char* str, int length)
{
int mstrlen = 0;
int spacelen = 0;
for (int i = 0; str[i] != '.'; i++)
{
mstrlen++;
if (str[i] == ' ')
spacelen += 3;
}
int newlength = mstrlen + spacelen;
if (newlength > length)
return NULL;
while (mstrlen >= 0 && newlength > mstrlen)
{
if (str[mstrlen] == ' ')
{
str[newlength--] = '0';
str[newlength--] = '2';
str[newlength--] = '%';
}
else
str[newlength--] = str[mstrlen];
mstrlen--;
}
return str;
}
};
int main()
{
Solution s;
char str[46] = {"We are happy. " };
cout << str << endl;
cout << s.replaceSpace(str, 46) << endl;
return 0;
}