As Commodore Jaeger said, I don't think any other answers actually answer this question; The question asks how to repeat a string, not a character.
Although Commodore's answer is correct, it is rather inefficient. Here's a faster implementation, the idea is to minimize copy and memory allocation operations by exponentially expanding the string first:
#include <string> #include <cstddef> std::string repeat(std::string str, const std::size_t n) { if (n == 0) { str.clear(); str.shrink_to_fit(); return str; } else if (n == 1 || str.empty()) { return str; } const auto period = str.size(); if (period == 1) { str.append(n - 1, str.front()); return str; } str.reserve(period * n); std::size_t m {2}; for (; m < n; m *= 2) str += str; str.append(str.c_str(), (n - (m / 2)) * period); return str; }
We can also define operator* to get something closer to the Python version:
#include <utility> std::string operator*(std::string str, std::size_t n) { return repeat(std::move(str), n); }
On my machine, this is about 10 times faster than the Commodore implementation, and about 2 times faster than the naive "add n - 1 time" solution.
Daniel Dec 16 '15 at 20:39 2015-12-16 20:39
source share