如何通过分隔符标记字符串?

How to tokenize string by delimiters?

我需要用定界符标记字符串。

例如:

对于 "One, Two Three,,, Four" 我需要得到 {"One", "Two", "Three", "Four"}.

我正在尝试使用这个解决方案

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): error C2228: left of '.begin' must have class/struct/union type is 'const char *const'

改变这个:

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

为此:

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

Link: http://www.boost.org/doc/libs/1_57_0/libs/tokenizer/tokenizer.htm

容器类型需要begin()函数,const char*(也就是c_str())returns不满足这个要求

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 表示您的 ,,, 输入不应该在这些逗号之间暗示 空字符串标记

我看到很多 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可以是任何trim函数,我用的是this SO answer。它利用 std::back_inserter 和递归。你可以很容易地循环完成,但这听起来更有趣:)

捷径。

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