1, 字符串的分割算法(標准庫版)
void split(const string& s,char c,vector<string>& v)
{
string::size_type i = 0;
string::size_type j = s.find(c);
while (j != string::npos)
{
v.push_back(s.substr(i,j-i));
i = ++j;
j = s.find(c,j);
if (j == string::npos)
v.push_back(s.substr(i,s.length()) );
}
}
template <typename T>
void split(basic_string<T>& s,T c,vector<basic_string<T> >& v)
{
typename basic_string<T>::size_type i = 0;
typename basic_string<T>::size_type j = s.find(c);
while (j != basic_string<T>::npos)
{
v.push_back(s.substr(i,j-i));
i = ++j;
j = s.find(c,j);
if (j == basic_string<T>::npos)
{
v.push_back(s.substr(i,s.length()) );
}
}
}
2,字符串的分割算法(boost庫實現)
int main()
{
string _str = "I|am|a|bad|boy";
list<string> myList;
split(myList,_str,is_any_of("|")); // 這裡用到了boost組庫的方法:split.
list<string>::iterator p;
for (p = myList.begin(); p != myList.end(); ++p)
{
cout << *p << " ";
}
cout << endl;
/***********************************************/
return 0;
}