c++ join split

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

template<class S, class T>

std::string join_str(std::vector<T>& elems, S& delim) {

    std::stringstream ss;

    typename std::vector<T>::iterator e = elems.begin();

    ss << *e++;

    for (; e != elems.end(); ++e) {

        ss << delim << *e;

    }

    return ss.str();

}

std::vector<std::string> split_str(const std::string& s, char delimiter){

    std::vector<std::string> tokens;

    std::string token;

    std::istringstream tokenStream(s);

    while ( std::getline(tokenStream, token, delimiter) )

        tokens.push_back(token);

    return tokens;

}

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

测试的代码:

    vector< string >vv = { "a", "b", "c" };

    std::string outStr = join_str( vv, "|" );

    vector< string > vv2 = split_str(  outStr,  '|' );

猜你喜欢

转载自blog.csdn.net/yangzm/article/details/81985632