简体   繁体   中英

replace the occurrence of character with a seq number using boost

How can i replace multiple occurrences of a character with a string containing the occurrence number. eg if i have the following expression.

insert into emp values(?,?,?)

I want the following converted string.

insert into emp values(_p_1,_p_2,_p_3)

I am trying this using the boost regular expression.

Can anyone tell me how to achieve this using the boost c++ (with no or minimum iteration).

currently I am using the following approach:

        std::wstring q=L"insert into emp values(?,?,?)";
        auto loc = q.find(L"?");
        auto len = wcslen(L"?");
        auto c=1;
        while(loc != std::wstring::npos)
        {
            q.replace(loc, len , L"_p_"+to_wstring(c));
            c++;
            loc = q.find(L"?");
        }
        cout<<q.c_str();

Please suggest better and efficient approaches.

I'd just forget regular expressions and trying to do this simple thing with Boost.

It's like asking, "how do I add 1 to a variable using Boost regular expressions"?

Best answer, IMHO, is to instead just use ++ for the task of adding 1, and to use a loop to replace special characters with strings.

string const query_format = "insert into emp values(?,?,?)";
string const params[] = {"_p_1", "_p_2", "_p3"};

string query;
string const* p = params;
for( char const c : query_format )
{
    if( c == '?' ) { query += *p++; } else { query += c; }
}
// Use `query`

One might choose to wrap this up as a replace function.

Disclaimer: code not touched by compiler.


If you control the query_format string, why not instead make the placeholders compatible with Boost format .


Re the parenthetical requirement

with no or minimum iteration

there's iteration involved no matter how you do this. You can hide the iteration behind a function name, but that's all. It's logically impossible to actually avoid the iteration, and it's trivial (completely trivial) to hide it behind a function name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM