【发布时间】:2015-06-12 07:38:06
【问题描述】:
我正在尝试拆分字符串并将其放入向量中
但是,只要有连续的分隔符,我也想保留一个空标记:
例如:
string mystring = "::aa;;bb;cc;;c"
我想在 :; 上标记这个字符串分隔符 但在分隔符之间,例如 :: 和 ;; 我想在我的向量中推入一个空字符串;
so my desired output for this string is:
"" (empty)
aa
"" (empty)
bb
cc
"" (empty)
c
另外我的要求是不要使用 boost 库。
如果有的话可以给我一个想法。
谢谢
标记字符串但不包含空标记的代码
void Tokenize(const string& str,vector<string>& tokens, const string& delim)
{
// Skip delimiters at beginning.
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
}
【问题讨论】:
-
你有没有尝试过?
-
我尝试了上面的代码来标记我的字符串,但它只排除了空标记
-
为什么不在
tokens.push_back(str.substr(lastPos, pos - lastPos));之后添加tokens.push_back("");? -
我猜这不可能,如果是不同的字符串呢?
-
尝试用其他东西替换
find_first_not_of(可能是简单的加1)。