hydra123 hydra123 - 3 years ago 85
C++ Question

Replace double single quote (' ') with a single quote (')

Suppose I have a string :

argsStr = "server ('m1.labs.terad ''ata.com') username ('us ''er5') password('user)5') dbname ('def\\ault')";

Now I am using the following code to extract the tokens:

'm1.labs.terad ''ata.com' <- token1
'us ''er5' <-token2
'user)5' <-token3
'def\ault' <-token4


regex re("(\'(.*?)\'\)");
typedef std::vector<std::string> StringVector;
StringVector arg_values;
boost::regex re_arg_values("('[^']*(?:''[^']*)*')");
boost::sregex_token_iterator name_iter_start(argsStr.begin(),argsStr.end(), re_arg_values, 0),name_iter_end;
std::copy(value_iter_start, value_iter_end,std::back_inserter(arg_values));
//putting the token in the string vector.

Now after putting it into the string vector, How can I convert the tokens/ string to replace double quotes with single quotes:

For example:

'm1.labs.terad ''ata.com'
should become
'm1.labs.terad 'ata.com'
'us ''er5'
should become
'us 'er5'

Can I use boost::replace_all for this?

Answer Source

Replace Substring with Substring in a String Using a For Loop

Here we replace a substring with another substring and return the amended string. We pass in the string to be changed, the string we want to find and the string we want to replace it with, s, s_to_replace and s_replace.

find() searches and finds the first character of the string passed in and returns an iterator at that position. std::string::npos this value is greatest possible value size_t can reach, i.e. the end of the string. std::string::erase takes the position of the first character and the number of characters to replace and erases them. std::string::insert takes position of where to insert and the string to insert and does just that.

std::string replace_substring(string s, const string s_to_replace, const string s_replace) {
    for(size_t position = 0; ; position += s_replace.length()) {

        position = s.find(s_to_replace, position);

        if(position == string::npos || s.empty()) break;

        s.erase(position, s_to_replace.length());
        s.insert(position, s_replace);
        // s.replace(position, s_to_replace.length(), s_replace)
    return s;

Replace Substring with Substring in a String Using Boost

#include <boost/algorithm/string/replace.hpp>

boost::replace_all(s, s_to_replace, s_replace);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download