题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路:
- 从前往后轮训,遇到空格替换“%20”,将空格后每个数据后移两个单位距离,所以:
- 先线轮训判断空格数量n,之后从后向前,每遇到一个空格前将每个元素向后移动(n-i)*2个单位,空格处开始替换为“%20”
------------------------------------------------
示例:
输入:" helloworld";
输入出:"%20helloworld"
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
using namespace std;
void replaceSpace(char *str,int length){
int space = 0, oldLength = 0;
for (int i = 0; *(str + i) != '\0'; ++i) {
if(*(str+i) == ' ')
space++;
oldLength++;
}
//新字符串的长度
int newLength = oldLength + space * 2;
//如果新的字符串大于开辟的空间,发生溢出,退出函数
if(newLength + 1 > length)
return;
for (int j = oldLength-1; j >=0&&space!=0 ; --j) {
//不是空格将后移(j+space*2)个单位
if(*(str+j) != ' '){
*(str+j+space*2) = *(str+j);
}
//如果是空格,则后移(j+(space-1)*2)个单位,并插入"%20"
else if (*(str+j) == ' ')
{
*(str+j+(space-1)*2) = '%';
*(str+j+1+(space-1)*2) = '2';
*(str+j+2+(space-1)*2) = '0';
space--;
}
}
//
*(str+newLength) = '\0';
}
int main()
{
char str[20] = " helloworld";
replaceSpace(str,20);
cout << str ;
return 0;
}