Is there a way to implement analog of Python's 'separator'.join() in C++?

后端 未结 6 616
傲寒
傲寒 2021-02-07 03:44

All I\'ve found is boost::algorithm::string::join. However, it seems like overkill to use Boost only for join. So maybe there are some time-tested recipes?

<
6条回答
  •  暖寄归人
    2021-02-07 04:28

    Here is another version that I find more handy to use:

    std::string join(std::initializer_list initList, const std::string& separator = "\\")
    {
        std::string s;
        for(const auto& i : initList)
        {
            if(s.empty())
            {
                s = i;
            }
            else
            {
                s += separator + i;
            }
        }
    
        return s;
    }
    

    You can then call it this way:

    join({"C:", "Program Files", "..."});
    

提交回复
热议问题