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.
forloop) andswitchon each character.Use a
std::ostringstreamfor 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::stringas the output buffer, append the characters usingpush_back, andreservea sufficiently large capacity (e.g.1.5 * input.length()) in front of the loop.