How to insert a character every N characters in a string in C++

后端 未结 5 1011
说谎
说谎 2021-01-14 05:33

How can I insert a character into a string exactly after 1 character?

I need to insert \'|\' into the string after every other char

5条回答
  •  春和景丽
    2021-01-14 06:07

    I think I'd use a standard algorithm and iterator:

    std::string add_seps(std::string const &input, std::string sep="|") { 
        std::ostringstream os;
        std::copy(input.begin(), input.end(), std::ostream_iterator(os, sep));
        return os.str();
    }
    

    As it stands, this adds a separator after the last character of the input. If you only want them between characters, you'd use an infix_ostream_iterator.

提交回复
热议问题