【问题标题】:replace single quotes in string with \'用\'替换字符串中的单引号
【发布时间】:2011-03-17 16:26:39
【问题描述】:

我有一个包含 ' 字符的字符串。我想用 \' 替换所有这些,因为它用于插入数据库。有人可以建议我一种有效的方法吗?不幸的是,我不能使用 boost 并且仅限于 STL。

【问题讨论】:

  • 提示:不要像那样清理您的输入,只需使用参数查询并忘记此类问题。您使用的是什么数据库库?
  • 它的 DB2。不幸的是,有一大笔遗产,我目前无法做出如此重大的改变。但我还是很想知道参数化查询方法。

标签: c++ string stl


【解决方案1】:

当\ 出现在源字符串中时,别忘了也转义它。

std::string escape(std::string const &s)
{
    std::size_t n = s.length();
    std::string escaped;
    escaped.reserve(n * 2);        // pessimistic preallocation

    for (std::size_t i = 0; i < n; ++i) {
        if (s[i] == '\\' || s[i] == '\'')
            escaped += '\\';
        escaped += s[i];
    }
    return escaped;
}

【讨论】:

    【解决方案2】:

    最好是复制到一个新的字符串中,因为这样效率更高,否则每次插入一个字符时,它都会移动字节,这是非常低效的。此外,您可能会发现很难保持迭代器有效。

    最简单的方法是编写一个循环来创建新的循环,尽管您可以使用函子在每次迭代时插入新字符串。

    struct escaper
    {
      std::string& target;
      explicit escaper( std::string& t ) : target( t ) {}
    
      void operator()( char ch ) const
      {
         if( ch == '\'') // or switch on any character that 
                         // needs escaping like \ itself
         {
            target.push_back('\\');
         }
         target.push_back( ch );
      }
    };
    
    std::string escaped;
    std::for_each( instr.begin(), instr.end(), escaper(escaped));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-07
      • 2021-12-22
      • 1970-01-01
      • 2019-11-02
      • 2023-03-23
      • 1970-01-01
      相关资源
      最近更新 更多