2016-08-15 25 views
-1

andのいずれかの文字列を分割したい。C++分割文字列全体として別の文字列

最初に、私は区切り文字として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」とは、文字列内の任意の文字と一致するものです。 3番目の引数はlambdaを含む任意の呼び出し可能なオブジェクトであることを意味する*述語*です。別の問題は、[boost :: split'](http://www.boost.org/doc/libs/1_61_0/doc/html/boost/algorithm/split_idp205739088.html)が*文字ベースであるように見えることです。 「単語」に基づくものではありません。 –

+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」が含まれていると、含まれている「and」を「split」します。 –

+0

find()が失敗した場合、 'substr(pos、npos-pos)'を呼び出す際にエラーが発生します。 –

+0

@DavidThomas Re:contains "and"。問題の声明には、プログラムがそれを分割してはならないことは何も示唆されていません。 Quot the OP:* "私は文字列を**と**の任意の**出現で分割したい。" *(emphasis mine)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(); 
}