0

文字列を区切り記号でトークン化する必要があります。

例えば:

"One, Two Three,,, Four"を取得する必要があるためです{"One", "Two", "Three", "Four"}

私はこのソリューションを使用しようとしています https://stackoverflow.com/a/55680/1034253

std::vector<std::string> strToArray(const std::string &str,
                                    const std::string &delimiters = " ,")
{
    boost::char_separator<char> sep(delimiters.c_str());
    boost::tokenizer<boost::char_separator<char>> tokens(str.c_str(), sep);

    std::vector<std::string> result;
    for (const auto &token: tokens) {
        result.push_back(token);
    }

    return result;
}

しかし、私はエラーが発生します:

boost-1_57\boost/tokenizer.hpp(62): エラー C2228: '.begin' の左側には class/struct/union 型が 'const char *const' である必要があります

4

4 に答える 4

2

これを変える:

boost::tokenizer<boost::char_separator<char>> tokens(str.c_str(), sep);

これに:

boost::tokenizer<boost::char_separator<char>> tokens(str, sep);

リンク: http://www.boost.org/doc/libs/1_57_0/libs/tokenizer/tokenizer.htm

コンテナー型にはbegin()関数が必要であり、 const char* ( c_str()) が返すものはこの要件を満たしていません。

于 2015-02-05T22:30:58.577 に答える
1

近道。

string tmp = "One, Two, Tree, Four";
int pos = 0;
while (pos = tmp.find(", ") and pos > 0){
    string s = tmp.substr(0, pos);
    tmp = tmp.substr(pos+2);
    cout << s;
}
于 2015-09-13T04:58:49.140 に答える
1

Boostのトークナイザーは、あなたが説明したタスクにはおそらくやり過ぎです。

boost::splitこの正確なタスクのために書かれました。

std::vector<std::string> strToArray(const std::string &str,
                                    const std::string &delimiters = " ,")
{
    using namespace boost;
    std::vector<std::string> result;
    split( result, str, is_any_of(delimiters), token_compress_on );
    return result;
}

そのオプションtoken_compress_onは、入力がそれらのコンマの間の空の文字列トークン,,,を暗示してはならないことを意味します。

于 2015-02-05T22:31:14.647 に答える
0

私はたくさんのboost答えを見ているので、私は非答えを提供すると思ったboost

template <typename OutputIter>
void Str2Arr( const std::string &str, const std::string &delim, int start, bool ignoreEmpty, OutputIter iter )
{
    int pos = str.find_first_of( delim, start );
    if (pos != std::string::npos) {
        std::string nStr = str.substr( start, pos - start );
        trim( nStr );

        if (!nStr.empty() || !ignoreEmpty)
            *iter++ = nStr;
        Str2Arr( str, delim, pos + 1, ignoreEmpty, iter );
    }
    else
    {
        std::string nStr = str.substr( start, str.length() - start );
        trim( nStr );

        if (!nStr.empty() || !ignoreEmpty)
          *iter++ = nStr;
    }
}

std::vector<std::string> Str2Arr( const std::string &str, const std::string &delim )
{
    std::vector<std::string> result;
    Str2Arr( str, delim, 0, true, std::back_inserter( result ) );
    return std::move( result );
}

trim任意のトリム関数にすることができます。私はこの SO answerを使用しました。std::back_inserterと再帰を利用します。ループで簡単に実行できますが、これはもっと楽しいように聞こえました:)

于 2015-02-05T22:57:04.407 に答える