#include <stdio.h>
#include <iostream>
using namespace std;
class Solution{
public:
void replaceSpace(char str[],int length) {
//合法性检验
if(str == NULL || length <= 0)
return;
//计算实际长度和替换后的长度
int i=0, count=0;
while(str[i] != '\0')
{
if(str[i] == ' ')
count++;
++i;
}
int oriIndex = i, newIndex = oriIndex + count * 2;
if(newIndex < oriIndex)
return;
//逆序移动 循环结束条件两个指针指到相同位置
while(newIndex != oriIndex)
{
//旧索引处发现空格,新索引处替换并添加
if(str[oriIndex] == ' ')
{
str[newIndex--] = '0';
str[newIndex--] = '2';
str[newIndex--] = '%';
}
else//未发现 复制原先位置字符
{
str[newIndex] = str[oriIndex];
newIndex--;
}
//无论是否发现,旧索引都需要向前移动一个索引
--oriIndex;
}
}
};
int main()
{
char str[100] = " We are happy.";
int len = sizeof(str) / sizeof(char);
Solution sol;
sol.replaceSpace(str,100);
cout<<str<<endl;
}