str_helper.hpp 2.18 KB
/*
 * @Author: yangzilong
 * @Date: 2021-12-01 16:47:49
 * @Last Modified by: yangzilong
 * @Last Modified time: Do not edit
 * @Email: yangzilong@objecteye.com
 * @Description:
 */
#pragma once

#include <vector>
#include <cstring>
#include <sstream>
namespace helpers
{
    namespace string
    {
        std::vector<std::string> split_string(const std::string &str, char delim)
        {
            std::stringstream ss(str);

            std::string item;
            std::vector<std::string> elems;
            while (std::getline(ss, item, delim))
                elems.emplace_back(std::move(item));
            return std::move(elems);
        }

        template<typename Dtype = std::string>
        std::string join_string(const std::vector<Dtype> &vec, const std::string &join_str)
        {
            auto to_string_func = [](Dtype &val)
            {
                std::string it = "";
                if (std::is_same<std::string, decltype(val)>::value)
                    it = val;
                else
                    it = std::to_string(val);  // simple transfer...
                return it;
            };

            std::string res = "";
            for (Dtype val: vec)
                res.append(to_string_func(val) + join_str);
            return res.substr(0, res.length() - join_str.length());
        }

        std::string replace(const std::string &src, const std::string &replace_src, const std::string &replace_dst)
        {
            std::string src_copied = src;
            auto find_result = src_copied.find(replace_src);
            if (find_result != std::string::npos)
                src_copied.replace(find_result, replace_src.length(), replace_dst);
            return src_copied;
        }


        std::string replace_all(const std::string &src, const std::string &replace_src, const std::string &replace_dst)
        {
            std::string src_copied = src;
            while (true)
            {
                std::string src_temp = src_copied;
                if (src_temp == (src_copied = replace(src_copied, replace_src, replace_dst)))
                    break;
            }
            return src_copied;
        }

    }  // namespace string
} // namespace helper