题目:请实现一个函数,把字符串中的每个空格替换成"%20"。例如输入"We are happy.",则输出"We%20are%20happy."。
#include <iostream>
#include <cstdio>
using namespace std;
void replace_space(char s[], int maxLength);
int main()
{
char str[16] = "we are happy.";
replace_space(str, 16);
printf("%s\n", str);
return 0;
}
//时间复杂度为O(n)
void replace_space(char s[], int maxLength)
{
if(s == NULL && maxLength <= 0)
return;
int oriLength = 0;
int numOfSpace = 0;
int i = 0;
while(s[i] != '\0')
{
oriLength++;
if(s[i] == ' ')
{
numOfSpace++;
}
i++;
}
int newLength = oriLength + numOfSpace * 2;
if(newLength > maxLength)
{
printf("out of length.\n");
return;
}
int flag1 = oriLength;
int flag2 = newLength;
int count_space = 0;
while(count_space <= numOfSpace)
{
if(s[flag1] == ' ')
{
count_space++;
flag1--;
s[flag2--] = '0';
s[flag2--] = '2';
s[flag2--] = '%';
}
else
s[flag2--] = s[flag1--];
}
}