简体   繁体   English

使用boost将出现的字符替换为seq数字

[英]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. 我正在尝试使用boost正则表达式。

Can anyone tell me how to achieve this using the boost c++ (with no or minimum iteration). 谁能告诉我如何使用boost c ++(无迭代或最小迭代)实现这一目标。

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. 我只是忘记了正则表达式,而是尝试使用Boost做这个简单的事情。

It's like asking, "how do I add 1 to a variable using Boost regular expressions"? 这就像问“如何使用Boost正则表达式将1加到变量中”?

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. 最好的答案,恕我直言,而是使用++来执行加1的任务,并使用循环将特殊字符替换为字符串。

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. 可以选择将其包装为replace功能。

Disclaimer: code not touched by compiler. 免责声明:编译器未触及的代码。


If you control the query_format string, why not instead make the placeholders compatible with Boost format . 如果您控制query_format字符串,为什么不使占位符与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. 从逻辑上讲,实际上避免迭代是不可能的,并且将其隐藏在函数名后面是微不足道的(完全琐碎的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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