为什么用%20程序崩溃替换空格

why replace spaces with %20 program crashes?

本文关键字:替换 空格 崩溃 程序 为什么      更新时间:2023-10-16

我编写了以下代码,用字符串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不断更新。