开发者

String handling in C++

开发者 https://www.devze.com 2023-01-05 02:57 出处:网络
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?

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开发者_StackOverflow中文版 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?


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消