How do I write a function in C++ that takes a string s
and an integer n
as input and gives at output a string that has spaces placed every n
characters in s
?
For example, if the input is s = "abcdefgh"
and n = 3
then the output should be "abc def gh"
EDIT:
I could have used loops for this but I am looking for concise and an idiomatic C++ solution (i.e. the one that uses algorithms from STL).
EDIT:
Here's how I would I do it in Scala (which happens to be my primary language):
def drofotize(s: String, n: Int) = s.grouped(n).toSeq.flatMap(_ + " ").mkString
Is this level of conciseness possible with C++? Or do I have to use explicit loops after all?