利用新字符串进行更新
class Solution {
public:
string replaceSpaces(string &str) {
string res;
for(char c : str)
{
if(c==' ')res+="%20";
else res+=c;
}
return res;
}
};
利用replace(起始位置(int),待替换字符长度(int),替换字符(string))进行替换
class Solution {
public:
string replaceSpaces(string &str) {
while(str.find(" ")!=string::npos)
{
int pos = str.find(" ");
str.replace(pos,1,"%20");
str.find(" ",pos+3);
}
return str;
}
};