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.
- Go over the string in a single pass (
for
loop) andswitch
on each character. - When encountering a character that needs escaping, push a backslash into the output buffer
- 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.
精彩评论