1、题目
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
2、程序1
确定变换后数组的长度,再从后往前更新数组,记得在最开始要先加’\0’
class Solution {
public:
void replaceSpace(char *str,int length) {
int spacenum = 0,strlen = 0;
for(int i = 0; i < length; ++i){
if(str[i] == ' ') spacenum++;
else if (str[i] == '\0') break;
strlen++;
}
int newstrlen = strlen + spacenum * 2;
int j = newstrlen;
str[j--] = '\0';
for(int i = strlen - 1; i >= 0; --i){
if(str[i] == ' '){
str[j--] = '0';
str[j--] = '2';
str[j--] = '%';
}
else str[j--] = str[i];
}
}
};
3、程序2
重新定义一个新的数组,并逐个进行赋值,然后进行空格的替换
class Solution {
public:
void replaceSpace(char *str,int length) {
char *tmp = (char*)malloc(sizeof(char) * length);
for(int i = 0; i < length; ++i){
tmp[i] = str[i];
}
int j = 0;
for(int i = 0; i < length; ++i){
if(tmp[i] != ' '){
str[j++] = tmp[i];
} else{
str[j++] = '%';
str[j++] = '2';
str[j++] = '0';
}
}
}
};
class Solution {
public:
void replaceSpace(char *str,int length) {
char *tmp = (char*)malloc(sizeof(char)*length);
for(int i = 0; i < length; ++i) tmp[i] = str[i];
int j = 0;
for(int i = 0; i < length; ++i){
if(tmp[i] == ' '){
str[j++] = '%';
str[j++] = '2';
str[j++] = '0';
}
else if(tmp[i] == '\0'){
str[j++] = '\0';
break;
}
else str[j++] = tmp[i];
}
}
};