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

天大地大妈咪最大 提交于 2019-12-06 11:09:42
std::string tokenize(const std::string& s) {
   if (!s.size()) {
     return "";
   }
   std::stringstream ss;
   ss << s[0];
   for (int i = 1; i < s.size(); i++) {
     ss << '|' << s[i];
   }
   return ss.str();
}
Jerry Coffin

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<char>(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.

You can use

string& insert (size_t pos, const string& str);

You would have to loop through the string, inserting a character each time.

for (int i = 1; i < str.size(); i++) {
      str << str.insert(i, '|');
      i++;
}

Here is my C++11 example (with gcc 4.7):

#include <string>
#include <iostream>

template<const unsigned num, const char separator>
void separate(std::string & input)
{
    for ( auto it = input.begin(); (num+1) <= std::distance(it, input.end()); ++it )
    {
        std::advance(it,num);
        it = input.insert(it,separator);
    }
}

int main(void)
{
    std::string input{"aaffbb3322ff77c"};
    separate<3,' '>(input);
    std::cout << input << std::endl;
    separate<4,'+'>(input);
    std::cout << input << std::endl;
    return 0;
}

The result output is:

aaf fbb 332 2ff 77c

aaf +fbb +332 +2ff +77c

Here's a slightly different approach that will only do 1 allocation for the resultant string so it should be slightly more efficient than some other suggestions.

std::string AddSeparators(const std::string & s)
{
    if(s.size() <= 1)
        return s;

    std::string r;
    r.reserve((s.size()*2)-1);
    r.push_back(s[0]);
    for(size_t i = 1; i < s.size(); ++i)
    {
        r.push_back('|');
        r.push_back(s[i]);
    }
    return r;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!