时间限制:1秒 空间限制:32768K 热度指数:740599
本题知识点: 字符串
题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
#include<iostream>
using namespace std;
#include<cstring>
void replaceSpace(char *str, int length);
void main(){
char *a = "hello world";
replaceSpace(a, 20);
cout << a;
system("pause");
}
void replaceSpace(char *str, int length) {
int origin = 0;
int blank = 0;
for (int i = 0; i < length; i++)
{
if (str[i] == ' ')
{
blank++;
}
origin++;
}
int newlength = origin + 2 * blank;
if (newlength > length)
{
return;
}
int index_origin = origin;
int index_new = newlength;
while ((index_origin >= 0 )&& (index_new > index_origin))
{
if (str[index_origin] == ' ')
{
str[index_new--] = '0';
str[index_new--] = '2';
str[index_new--] = '%';
}
else
{
str[index_new--] = str[index_origin];
}
}
}