思路是使用棧的模式從後部開始然後向前追加方式
#include <iostream>
using namespace std;
/*請實現一個函數,將一個字符串中的空格替換成“ % 20”。
例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are % 20Happy*/
void replaceSpace(char *str, int length)
{
char *dest = str;
int n = 0;
for (int i = 0; i < length; i++)
{
if (str[i] == ' ')
n++;
}
int j = length+n*2-1;
for (int i = length-1; i >=0; i--)
{
if (dest[i] == ' ')
{
str[j--] = '0';
str[j--] = '2';
str[j--] = '%';
}
else
{
str[j--] = dest[i];
}
}
}
int main()
{
char str[100] = " hello world ";
replaceSpace(str, strlen(str));
cout << str;
}