2016-08-15 240 views
-1

我想分割任何出现的字符串andC++将整个字符串拆分为另一个字符串

首先我必须说清楚,我不打算使用任何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,除非您确定它可以用于我的情况。

+2

这就是'is_any_of'的意思,它与*字符串中的任何*字符匹配。第三个参数是* predicate *,这意味着它可以是任何可调用的对象,包括lambda。另一个问题是['boost :: split'](http://www.boost.org/doc/libs/1_61_0/doc/html/boost/algorithm/split_idp205739088.html)似乎是基于* character *的,而不是“单词”的基础。 –

+0

@JoachimPileborg,谢谢你的评论。要替换什么? – jeremine

回答

0

老式的方式:

#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; 
} 

包装成一个可重用的功能就留给读者自己练习。

+0

如果扫描的文本包含“Copeland,Amit”...,您将“包含”和“”分开。 –

+0

如果find()失败,那么调用'substr(pos,npos-pos)' –

+0

@DavidThomas Re:contains“and”时会出错。问题陈述中没有任何内容表明该计划不应该分裂。猜测的OP:*“我想分割一个字符串**任何**出现的'和'。”*(强调我的)Re:'substr' - 不,我没有错误。该程序实际上预计最终会调用'substr(pos,npos-pos)',并且它工作得很好。 –

1

<algorithm>包含搜索 - 此任务的正确工具。

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(); 
} 
相关问题