views:

150

answers:

2

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?

+2  A: 

Copy each character in a loop and when i>0 && i%(n+1)==0 add extra space in the destination string.


As for Standard Library you could write your own std::back_inserter which will add extra spaces and then you could use it as follows:

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

but I could say that writing such a functor is just a wasting of your time. It is much simpler to write a function copy_with_spaces with an old good for-loop in it.

Kirill V. Lyadvinsky
Are you kidding me? Do you really think I can't even develop a looping logic? I want a more idiomatic (read: the one that uses STL) solution and that's why I posted the question here.
Daniel
@Daniel, you didn't even mentioned about STL in your original question. What are you really looking for? Could you be more specific in your question?
Kirill V. Lyadvinsky
@Kirill: Edited my post.
Daniel
@Daniel, edited my answer.
Kirill V. Lyadvinsky
This is the kind of answer I was looking for. Thanks. :) (Just add an EDIT after your first paragraph so that people know what's new and what was there in the original post.)
Daniel
+2  A: 

STL algorithms don't really provide anything like this. Best I can think of:

#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);
}
Ben Straub
Tail-recursive solution. Nice!
Daniel
We may be stuck in C++, but that doesn't mean we can't be civilized. ;)
Ben Straub