題目:請實現一個函數,把字符串中的每個空格替換成“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--;
}
}