【问题标题】:C++ split string by another string as wholeC++ 将另一个字符串作为一个整体分割字符串
【发布时间】:2016-08-15 07:17:38
【问题描述】:

我想通过and 的任何出现来拆分字符串。

首先我要明确一点,我不打算使用任何regex作为分隔符。

我运行以下代码:

#include <iostream>
#include <regex>
#include <boost/algorithm/string.hpp>

int main()
{
    std::vector<std::string> results;
    std::string text=
        "Alexievich, Svetlana and Lindahl,Tomas and Campbell,William";
    boost::split(
        results,
        text,
        boost::is_any_of(" and "),
        boost::token_compress_off
        );
    for(auto result:results)
    {
        std::cout<<result<<"\n";
    }
    return 0;
}

结果和我预期的不一样:

Alexievich,
Svetl







Li


hl,Tom
s




C
mpbell,Willi
m

似乎分隔符中的每个字符都是单独作用的,而我需要将整个 and 作为分隔符。

请不要链接到this boost example,除非您确定它适用于我的情况。

【问题讨论】:

  • 这就是is_any_of 的意思,它匹配字符串中的任何 个字符。第三个参数是一个 predicate,这意味着它可以是任何可调用对象,包括 lambda。另一个问题是boost::split 似乎是基于字符,而不是基于“单词”。
  • @JoachimPileborg,感谢您的评论。用什么代替?

标签: c++ string c++11 boost


【解决方案1】:

&lt;algorithm&gt; 包含用于此任务的搜索正确工具。

vector<string> results;
const string text{ "Alexievich, Svetlana and Lindahl,Tomas and Campbell,William" };
const string delim{ " and " };
for (auto p = cbegin(text); p != cend(text); ) {
    const auto n = search(p, cend(text), cbegin(delim), cend(delim));
    results.emplace_back(p, n);
    p = n;
    if (cend(text) != n) // we found delim, skip over it.
        p += delim.length();
}

【讨论】:

    【解决方案2】:

    老办法:

    #include <iostream>
    #include <string>
    #include <vector>
    
    int main()
    {
        std::vector<std::string> results;
        std::string text=
            "Alexievich, Svetlana and Lindahl,Tomas and Campbell,William";
        size_t pos = 0;
        for (;;) {
            size_t next = text.find("and", pos);
            results.push_back(text.substr(pos, next - pos));
            if (next == std::string::npos) break;
            pos = next + 3;
        }
    
        for(auto result:results)
        {
            std::cout<<result<<"\n";
        }
        return 0;
    }
    

    打包成一个可重用的函数留给读者作为练习。

    【讨论】:

    • 如果扫描的文本中包含“Copeland, Amit”...您将在包含的“and”上“拆分”。
    • 如果 find() 失败,则调用 substr(pos, npos-pos) 时出错
    • @DavidThomas Re:包含“和”。问题陈述中没有任何内容表明该程序不应该就此进行拆分。 Quoth OP:“我想通过 any 出现 and 来拆分字符串。”(强调我的)回复:substr - 不,我没有错误。该程序实际上预计最终会调用substr(pos, npos-pos),并且运行良好。
    • 我的立场是正确的。我知道 substr 会接受 npos 并返回字符串的其余部分,但从未见过比字符串长的任何值都可以做同样的事情。嗯。谢谢你的课。
    猜你喜欢
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多