题目:请实现一个函数,把字符串中的每个空格替换成“20%”,例如输入“We are happy.”,则输出“We%20are%20happy.”。
分析:
void test(string &str,int size)
{
if (size <= 0)
{
return;
}
int count = 0;//定义一个变量来计数空格的数量
for (int i = 0; i < size; i++)
{
if (str[i] == ' ')
{
count++;
}
}
int length = size + 2 * count;//新的size
if (length == size)
{
return;
}
str.resize(length);//将字符串的容量一次性扩到新的size
int right = length - 1;
int cur = size - 1;
while(size<right)//从后往前依次判断,如果不是空格,就放到right的位置,
//如果是空格,替换成“20%”
{
if (str[size] != ' ')
{
str[right--] = str[size];
}
else
{
str[right--] = '0';
str[right--] = '2';
str[right--] = '%';
}
size--;
}
}