开发者

The fastest solution to port the php function addslashes to c++

string addslashes ( string $str ) Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash () and NUL (the NULL byte).

I'm working on a c++ equivalent of this php function. Right now my function uses nested replace calls, where I replace \ with \\ and ' with \'. It's not pretty at开发者_运维知识库 all and it's very slow too.

What is the best solution using only the standard c++ libs and functions? I mean the absolute fastest way.


  1. Go over the string in a single pass (for loop) and switch on each character.
  2. When encountering a character that needs escaping, push a backslash into the output buffer
  3. Push current character into the output buffer.

Use a std::ostringstream for the output buffer.

This is very efficient (single pass, buffered output) and straightforward to implement. To make it yet more efficient, directly use a std::string as the output buffer, append the characters using push_back, and reserve a sufficiently large capacity (e.g. 1.5 * input.length()) in front of the loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜