<分区>
Possible Duplicate:
Splitting a string in C++
我从我的问题得到的答案之一得到了这个 vector 函数
vector<string> split(const string& s, char delim)
{
vector<string> elems(2);
string::size_type pos = s.find(delim);
elems[0] = s.substr(0, pos);
elems[1] = s.substr(pos + 1);
return elems;
}
但是,它只接受 2 个元素。如何根据字符串s中存在多少个分隔符修改为accept?
例如,如果我有这个:
user#password#name#fullname#telephone
有时大小可能会有所不同。
如何让这个函数无论有多少元素都能灵活工作,并且能够像上面这个函数一样拆分?
进一步解释我的问题:
我想要实现的是使用此 vector 函数进行拆分的能力,将相同的分隔符分隔为 N 大小,而不是固定为大小 2。
此函数最多只能拆分字符串中的 2 个元素,超过该值会导致 Segmentation core dump
像以前一样,我只需要使用
user:pass
现在我添加了更多属性,所以我需要能够拆分
user:pass:name:department
哪个x[2]和x[3]分别返回姓名和部门
他们都将使用相同的分隔符。
进一步更新:
我尝试使用下面答案之一提供的这个功能
vector<string> split(const string& s, char delim)
{
bool found;
vector<string> elems;
while(1){
string::size_type pos = s.find(delim);
if (found==string::npos)break;
elems.push_back(s.substr(0, pos));
s=s.substr(pos + 1);
}
return elems;
}
我得到了一些错误
server.cpp: In function ‘std::vector<std::basic_string<char> > split(const string&, char)’:
server.cpp:57:22: error: passing ‘const string {aka const std::basic_string<char>}’ as ‘this’ argument of ‘std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>, std::basic_string<_CharT, _Traits, _Alloc> = std::basic_string<char>]’ discards qualifiers [-fpermissive]