我有一个包含'字符的字符串.我想用\'替换所有这些,因为它用于插入数据库.有人可以建议我这样做的有效方法吗?不幸的是,我不能使用boost并限制为STL.
\当它在源字符串中出现时,不要忘记也要逃避.
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7177 次 |
| 最近记录: |