题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
class Solution {
public:
void replaceSpace(char *str,int length) {
char array[length];
int count = 0;
int temp[length];
for(int i = 0; i < length; i++){
temp[i] = 0;
}
for(int i = 0;i < length; i++){
array[i] = str[i];
if(str[i] == ' '){
count ++;
temp[i] = 1;
}
}
int spaceCount = 0;
for(int i = 0;i < length + count * 2; i++){
if(str[i] == ' '){
for(int j = length - 1 + spaceCount * 2; j > i; j-- ){
str[j + 2] = str[j];
}
str[i] = '%';
str[i+1] = '2';
str[i+2] = '0';
spaceCount++;
}
}
}
};