我试图拆分一个字符串并将其放入一个向量中
但是,每当有连续的分隔符时,我也想保留一个空标记:
例如:
string mystring = "::aa;;bb;cc;;c"
Run Code Online (Sandbox Code Playgroud)
我想将这个字符串标记为:; 分隔符,但在分隔符之间,如::和;; 我想在我的向量中插入一个空字符串;
so my desired output for this string is:
"" (empty)
aa
"" (empty)
bb
cc
"" (empty)
c
Run Code Online (Sandbox Code Playgroud)
另外我的要求是不要使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过一些简单的更改使您的算法工作。首先,不要在开头跳过分隔符,然后不要跳过字符串中间的分隔符,只需将位置加一。此外,您的npos检查应确保两个位置都不是npos这样,&&而不是||。
void Tokenize(const string& str,vector<string>& tokens, const string& delimiters)
{
// Start at the beginning
string::size_type lastPos = 0;
// Find position of the first delimiter
string::size_type pos = str.find_first_of(delimiters, lastPos);
// While we still have string to read
while (string::npos != pos && string::npos != lastPos)
{
// Found a token, add it to the vector
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Look at the next token instead of skipping delimiters
lastPos = pos+1;
// Find the position of the next delimiter
pos = str.find_first_of(delimiters, lastPos);
}
// Push the last token
tokens.push_back(str.substr(lastPos, pos - lastPos));
}
Run Code Online (Sandbox Code Playgroud)