分割格式化字符串的方法

来源:互联网 发布:明道软件电脑版下载 编辑:程序博客网 时间:2024/05/16 04:14

之前格式化字符串,都是用很low的方法sprintf, 最近学了boost库,就用boost来实现一下


#include <stdint.h>#include <boost/format.hpp>     #include <boost/tokenizer.hpp>     #include <boost/algorithm/string.hpp>    bool GetArray(const std::string &str, const std::string splitStr, std::vector<uint32_t> & v){typedef boost::tokenizer<boost::char_separator<char>> CustonTokenizer;boost::char_separator<char> sep(splitStr.c_str());CustonTokenizer tok(str, sep);v.clear();for (CustonTokenizer::iterator beg = tok.begin(); beg != tok.end(); ++beg){try{v.push_back(stoi(*beg));}catch (std::out_of_range & msg){std::cerr <<"out of range: "<< msg.what()<<std::endl;return false;}catch (...){return false;}}return true;}int main(int argc, char *argv[]){    std::string str = " 1,2,3,4";    std::vector<uint32_t> v;        if (!GetArray(str,",",v))    {        cout << "GetArray failed" << endl;        return 1;    }    std::vector<uint32_t>::iterator iter;    for (iter = v.begin(); iter != v.end();++iter)    {        cout << *iter << endl;    }    return 0;} 




0 0
原创粉丝点击