//使用临时字符串存储
string replaceSpace(string s) {
string ans;
for(char c:s)
{
if(c==' '){
ans.push_back('%');
ans.push_back('2');
ans.push_back('0');
}else
{
ans.push_back(c);
}
}
return ans;
}
不是用临时字符串
先计算出空格数量 space_cnt
再使用.resize(l +space_cnt*2)扩容
然后依次从最后填充。
string replaceSpace(string s) {
if (s.size() == 0) return s;
int ol = s.length();//字符串原来的长度
int space_cnt = 0;
for (char c : s)
{
if (c == ' ')
{
space_cnt++;
}
}
s.resize(ol + space_cnt * 2+1);
ol = ol - 1;
int j = ol + space_cnt * 2 ;
while (ol >= 0)
{
if (s[ol] == ' ')
{
ol--;
s[j--] = '0';
s[j--] = '2';
s[j--] = '%';
}
else
{
s[j--] = s[ol--];
}
}
return s;
}