我是C++的新手,我无法通过分隔符分割字符串,并将子字符串放入向量中。我如何将一个空字符串存储到一个向量中
我的代码如下:
vector<string> split(const string &s, const string &delim)
{
string::size_type pos = s.find_first_of(delim,0);
int start = 0;
vector<string> tokens;
while(start < s.size())
{
if(start++ != pos + 1)
tokens.push_back(" ");
pos = s.find_first_of(delim, start);
tokens.push_back(s.substr(start, pos - start));
}
for(vector<string>::size_type i = 0; i != tokens.size(); ++i)
cout << tokens[i];
return tokens;
}
字符串和分隔符被传递到函数和并执行分割。这个函数假设将空字符串放入向量中,但不会为我做。
例如,如果我调用该函数中主要为:
int main()
{
split("<ab><>cd<", "<>");
}
输出假设是
"","ab","","","","cd",""
减去报价
但输出为我的代码目前是
ab b cd d
任何帮助,将不胜感激。
这里有一些相关的问题,这可能有助于:http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c HTTP:/ /stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c http://stackoverflow.com/questions/4533652/how-to-split-string-using-istringstream-with- other-delimiter-than-whitespace http://stackoverflow.com/questio NS/5505965 /快字符串分割与 - 多定界符 – 2012-02-10 02:50:39