【C++】split
时间:2011-03-20 来源:撬棍
--------------------------------------------------1-------------------------------------------------------------------
#include <vector>
#include <string>
#include <boost/algorithm/string.hpp>
int main()
{
std::string str("1-56-89-52-41-56 ");
std::vector <std::string> result;
boost::algorithm::split(result, str, boost::algorithm::is_any_of( "- "));
}
--------------------------------------------------2-------------------------------------------------------------------
//////////////////////////////////////////////////////////////////////////////
// Function Name : split
// Description : split "source" with "delims" into string vector.
// Input Parameters : source -- the string with spliter
// delims -- the spliters
// vec -- output
// result -- string vector
// Return Value : how many slice had found.
//////////////////////////////////////////////////////////////////////////////
size_t split(const std::string& source,
const char *delims,
std::vector <std::string> &vec,
bool keepEmpty /*= false*/)
{
// find the index of which not delims
std::string::size_type beg = source.find_first_not_of(delims);
std::string::size_type end;
std::string::size_type nextBeg = beg;
while(std::string::npos != beg)
{
//find the index which is delims, than [beg, end] is the slice we want
end = source.find_first_of(delims, nextBeg + 1);
nextBeg = end;
if(end < beg)
{
//we find that case : two delims
if(keepEmpty)
vec.push_back(" ");
}
else if(std::string::npos != end)
{
vec.push_back(source.substr(beg, end - beg));
//update the begin index from the end index
beg = source.find_first_not_of(delims, nextBeg);
}
else
{
vec.push_back(source.substr(beg));
break;
}
}
return vec.size();
}