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

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

I need to insert '|' to the string after every other character.

In other words (C ++): "Tokens all around!"


Includes: "T|o|k|e|n|s| |a|l|l| |a|r|o|u|n|d|!"

(no, it is not an array)

thank

+1


source to share


5 answers


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();
}

      



+9


source


I think I would 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();
}

      



At its base, a separator is added after the last input character. If you only want them between characters, you should use infix_ostream_iterator

.

+3


source


you can use

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

      

You will have to iterate over the string, inserting the character each time.

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

      

+1


source


Here's a slightly different approach that will only do 1 selection for the resulting row, 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;
}

      

0


source


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;
}

      

Result result:

aaf fbb 332 2ff 77c

aaf + fbb +332 + 2ff + 77c

0


source







All Articles