String handling in C ++

How to write a function in C ++ that takes a string sand an integer nas input and outputs a string with spaces placed each ncharacter in s?

For example, if the input signal s = "abcdefgh"and n = 3, then the output should be"abc def gh"

EDIT:

I could use loops for this, but I am looking for a short and idiomatic solution in C ++ (i.e. one that uses algorithms from STL).

EDIT:

Here is how I could do it in Scala (which is my main language):

def drofotize(s: String, n: Int) = s.grouped(n).toSeq.flatMap(_ + " ").mkString

Is this level of conciseness possible with C ++? Or do I need to use explicit loops?

+3
source share
2 answers

i>0 && i%(n+1)==0 .


, std::back_inserter, , :

std::copy( str1.begin(), str1.end(), my_back_inserter(str2, n) );

, - . copy_with_spaces .

+2

STL . :

#include <string>
using namespace std;

string drofotize(const string &s, size_t n)
{
    if (s.size() <= n)
    {
        return s;
    }
    return s.substr(0,n) + " " + drofotize(s.substr(n), n);
}
+2

Source: https://habr.com/ru/post/1752533/


All Articles