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

自闭症网瘾萝莉.ら 提交于 2019-12-22 11:36:30

问题


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

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

In other words (C++): "Tokens all around!"
Turns into: "T|o|k|e|n|s| |a|l|l| |a|r|o|u|n|d|!" (no thats not an array)

Thanks


回答1:


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



回答2:


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.




回答3:


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



回答4:


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




回答5:


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


来源:https://stackoverflow.com/questions/27952032/how-to-insert-a-character-every-n-characters-in-a-string-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!