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

后端 未结 5 983
说谎
说谎 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<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.

    0 讨论(0)
  • 2021-01-14 06:09

    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;
    }
    
    0 讨论(0)
  • 2021-01-14 06:13

    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

    0 讨论(0)
  • 2021-01-14 06:17
    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();
    }
    
    0 讨论(0)
  • 2021-01-14 06:24

    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++;
    }
    
    0 讨论(0)
提交回复
热议问题