为什么用%20程序崩溃替换空格
why replace spaces with %20 program crashes?
我编写了以下代码,用字符串r(20%)替换字符串s中的所有空格。例如,s="Mr John Smith",运行代码后应为"Mr20%John20%Smith"。
我的代码崩溃了,在我看来就像内存泄漏,但不知道为什么会发生。非常感谢。
void ReplaceStr(string &s, string &r)
{
int i = 0;
for(string::iterator it = s.begin(); it != s.end(); it++,i++)
{
if( *it == ' ')
{
s.replace(i,1,r);
}
}
}
replace
的文档中说"任何与此对象相关的迭代器、指针和引用都可能无效。"迭代器是一个迭代器,它是一个不复存在的字符串版本,因此您不能不断增加、取消引用、比较它,等等。
当替换长度不等于目标大小时,构建副本通常更容易,效率也差不多。
void ReplaceSpaces(std::string &s, const std::string &r) {
std::string result;
result.reserve(s.size());
for (char c : s) {
if (c == ' ') result += r;
else result.push_back(c);
}
using std::swap;
swap(s, result);
}
一个更好的选择是根本不使用迭代器:
void ReplaceStr(string &s, string &r)
{
for (int i = 0; i < s.lenght(); )
{
if (s[i] == ' ')
{
s.replace(i,1,r);
i += r.lenght();
}
else
i++;
}
}
快速而简单。也许r的长度可以存储在一个常数中,以稍微提高性能。
void ReplaceStr(string &s, const string &r)
{
const int rSize = r.lenght();
for (int i = 0; i < s.lenght(); )
{
if (s[i] == ' ')
{
s.replace(i,1,r);
i += rSize;
}
else
i++;
}
}
这是因为s的leght不断更新。
相关文章:
- 模板参数替换失败,并且未完成隐式转换
- 在将 unicode 替换为C++字符串中的空格时出现分段错误
- 使用 Get 的 C++ 输入被替换为空格、不正确的数字
- '+'替换为空格 Curl C++
- 用递增的数字替换字符串中的空格
- 使用std::regex替换前导空格和尾随空格
- 替换字符串中空格的策略
- 如何将 ^M 替换为空格C++
- 用字符串中的空格替换符号
- visual C++-将空格替换为%20
- 程序错误:用"%20"替换空格
- 使用指针将输入中的空格替换为破折号符号
- 如何将 std::string 中的所有非字母字符(数字和特殊字符)替换为空格
- 将空白字符替换为 %20 的字符串,忽略所有尾随空格
- 将字符串中除空格外的所有字符替换为下划线
- 替换字符串中的空格
- 如何用c++字符串中的空格替换子字符串的所有出现
- 在c++中将字符串中的空格替换为%20
- 为什么用%20程序崩溃替换空格
- 将字符串中的所有空格替换为 '%20' (C++)