How to insert a character every N characters in a string in C ++
5 answers
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 to share
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 to share
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 to share