题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
解题思路:
题目关键在于求出替换后的数组的长度,然后想到从后往前替换空格。
另外需要注意是以’\0’作为判断结束的。
class Solution {
public:
//替换空格
void replaceSpace(char *str,int length) {
//检查数组是否为空
if(str == NULL){
return;
}
int countOfBlacks = 0;//空格个数
int originalLengths = 0;//替换前字符个数
int len = 0;//替换后字符个数
for(int i = 0;str[i]!='\0';i++){
originalLengths++;
if(str[i]==' '){
countOfBlacks++;
}
}
len = originalLengths + 2*countOfBlacks;
if(len+1 > length){//判断数组是否越界
return;
}
//替换空格:
int p1 = originalLengths;//指向替换前数组的末尾
int p2 = len;//指向替换后的数组的末尾
while(p1 < p2 && p1 >=0 ){
if(str[p1] == ' '){
str[p2--] = '0';
str[p2--] = '2';
str[p2--] = '%';
}else{
str[p2--] = str[p1];
}
p1--;
}
}
};