【C++】split

--------------------------------------------------1-------------------------------------------------------------------

void split(const std::string& src)
{
    stringstream ss;
    ss << src;
    while (!ss.eof())
    {
        std::string content;
        std::getline(ss, content, '|');
        std::cout << content << std::endl;
    }
}

--------------------------------------------------2-------------------------------------------------------------------

#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( "- ")); 

}

--------------------------------------------------3-------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////// 

// 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();

}

原文地址:https://www.cnblogs.com/fjfjfjfjfjfj/p/1989580.html