首页 > 其他分享 >cpp string split by delimeter and push back into vector

cpp string split by delimeter and push back into vector

时间:2023-02-12 15:11:26浏览次数:39  
标签:std string into back vector vec cpp split

void util::split_string_demo()
{
    std::string str=get_uuid();
    std::string delimiter="-";
    std::vector<std::string> vec;
    split_string(str,delimiter,vec);
    print_vector(vec);
    print_log(std::string(__FUNCTION__));
}

void util::print_vector(const std::vector<std::string> &vec)
{
    for(auto const &str:vec)
    {
        std::cout<<str<<std::endl;
    }
}

void util::split_string(std::string& str, const std::string& delimiter,std::vector<std::string> &vec)
{
    std::cout << str << std::endl; 
    std::string temp_str;
    int start = 0, end = 0;
    while ((end = str.find(delimiter, start)) != std::string::npos)
    {
        temp_str = str.substr(start, end-start);
        vec.push_back(temp_str);
        start = end + delimiter.length(); 
    } 
    temp_str=str.substr(start);
    if(!temp_str.empty())
    {
        vec.push_back(temp_str); 
    }    
}

void util::print_log(const std::string &str)
{
    std::cout << get_time_now() << ", in " << str << std::endl;
}

std::string util::get_time_now()
{
    std::chrono::time_point now = std::chrono::high_resolution_clock::now();
    time_t raw_time = std::chrono::high_resolution_clock::to_time_t(now);
    struct tm tm_info = *localtime(&raw_time);
    std::stringstream ss;
    auto mills = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
    auto seconds = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch());
    uint64_t mills_count = mills.count() - seconds.count() * 1000;
    ss << std::put_time(&tm_info, "%Y%m%d%H%M%S") << std::setw(3) << std::setfill('0') << mills_count;
    return ss.str();
}

std::string util::get_uuid()
{
    uuid_t new_uuid;
    uuid_generate(new_uuid);
    char *uuid_value = (char *)malloc(40);
    uuid_unparse(new_uuid, uuid_value);
    std::string uuid_str(uuid_value);
    free(uuid_value);
    return uuid_str;
}

 

g++ -std=c++2a -I. *.cpp ./model/*.cpp -o h1 -luuid -lpthread

 

 

 

Be cautious in cpp substring(start_index,length) method,the length is the length,instead of index

标签:std,string,into,back,vector,vec,cpp,split
From: https://www.cnblogs.com/Fred1987/p/17113841.html

相关文章