Search code examples
c++stringjsonquotation-marksjsoncpp

formatting a string which contains quotation marks


I am having problem formatting a string which contains quotationmarks.

For example, I got this std::string: server/register?json={"id"="monkey"}

This string needs to have the four quotation marks replaced by \", because it will be used as a c_str() for another function.

How does one do this the best way on this string?

{"id"="monkey"}

EDIT: I need a solution which uses STL libraries only, preferably only with String.h. I have confirmed I need to replace " with \".

EDIT2: Nvm, found the bug in the framework


Solution

  • it is perfectly legal to have the '"' char in a C-string. So the short answer is that you need to do nothing. Escaping the quotes is only required when typing in the source code

    std::string str("server/register?json={\"id\"=\"monkey\"}")
    my_c_function(str.c_str());// Nothing to do here
    

    However, in general if you want to replace a substring by an other, use boost string algorithms.

    #include <boost/algorithm/string/replace.hpp>
    #include <iostream>
    int main(int, char**)
    {
        std::string str = "Hello world";
        boost::algorithm::replace_all(str, "o", "a"); //modifies str
        std::string str2 = boost::algorithm::replace_all_copy(str, "ll", "xy"); //doesn't modify str
        std::cout << str << " - " << str2 << std::endl;
    }
    // Displays : Hella warld - Hexya warld