[英]How to tokenize string by delimiters?
我需要用定界符标记字符串。
例如:
对于"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'
更改此:
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()
)返回的值不满足此要求。
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
表示您的,,,
输入不应暗示这些逗号之间的空字符串标记 。
短路。
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;
}
我看到很多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答案 。 它利用了std::back_inserter
和递归。 您可以轻松地循环执行此操作,但这听起来更有趣:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.