1.replace 替换函数
class Solution
{
public:
string replaceSpaces(string &str)
{
for (int i = 0; i < str.size(); i++)
if (str[i] == ' ')
str.replace(i, 1, "%20");
return str;
}
};
2.字符串拼接
class Solution
{
public:
string replaceSpaces(string &str)
{
string res;
for (auto c : str)
{
if (c == ' ') res += "%20";
else res += c;
}
return res;
}
};
3.双指针
class Solution
{
public:
string replaceSpaces(string &str)
{
int len = 0;
for (auto c : str)
if (c == ' ') len += 3;
else len++;
int i = str.size() - 1, j = len - 1;
str.resize(len);
while (i >= 0)
{
if (str[i] == ' ') str[j--] = '0', str[j--] = '2', str[j--] = '%';
else str[j--] = str[i];
i--;
}
return str;
}
};