请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路一:计算元字符串中空格的个数,再将原来字符串的长度扩充到oldlength+2*spacecount个,然后将字符串从后往前挪,遇到空格就替换
实现代码:
class Solution {
public:
void replaceSpace(char *str,int length) {
if(str==NULL||length<=0){
return;
}
int i=0;
int spacecount=0;
int oldlength=0;
while(str[i]!='\0'){
oldlength++;
if(str[i]==' '){
spacecount++;
}
i++;
}
int newlength=oldlength+2*spacecount;
if(newlength>=length){//newlength不能等于length,为了给字符串的'\0'留位置
return ;
}
while(newlength>oldlength){
while(str[oldlength]!=' '){
str[newlength--]=str[oldlength--];
}
oldlength--;
str[newlength--]='0';
str[newlength--]='2';
str[newlength--]='%';
}
return ;
}
};
思路二:当给的字符串是string类型的一般就要考虑使用string的相关接口了。
class Solution {
public:
string replaceSpace(string iniString, int length) {
if (length == 0){
return iniString;
}
string newstr;
int i = 0;
for (i = 0; i < length; i++){
if (iniString[i] == ' '){
//newstr.push_back('%');
//newstr.push_back('2');
//newstr.push_back('0');
newstr+="%20";//此方法也同样可以实现
}
else{
newstr.push_back(iniString[i]);
}
}
return newstr;
}
};