182

I want to insert 'n' spaces (or any string) at the beginning of a string in C++. Is there a direct way to do this using either std::strings or char* strings?

E.g., in Python you could simply do

>>> "." * 5 + "lolcat"
'.....lolcat'
0

12 Answers 12

279

In the particular case of repeating a single character, you can use std::string(size_type count, CharT ch):

std::string(5, '.') + "lolcat"

This can't be used to repeat multi-character strings.

2
  • 158
    The OP asked for repeating a string, not a character. Commented Jan 20, 2016 at 21:10
  • 2
    @FlorianKaufmann At least this answer tried to help, and indeed it helps under particular situation when the length of the original string is 1. In contrary, your comment does not help the OP at all.
    – JSong
    Commented May 2 at 4:12
58

There's no direct idiomatic way to repeat strings in C++ equivalent to the * operator in Python or the x operator in Perl. If you're repeating a single character, the two-argument constructor (as suggested by previous answers) works well:

std::string(5, '.')

This is a contrived example of how you might use an ostringstream to repeat a string n times:

#include <sstream>

std::string repeat(int n) {
    std::ostringstream os;
    for(int i = 0; i < n; i++)
        os << "repeat";
    return os.str();
}

Depending on the implementation, this may be slightly more efficient than simply concatenating the string n times.

0
24

If the string to repeat is a single character string (as in your example), you can use one of the forms of string::insert:

std::string str("lolcat");
str.insert(0, 5, '.');

This will insert "....." (five dots) at the start of the string (position 0).

4
  • 48
    The OP asked for repeating a string, not a character.
    – Brent
    Commented Dec 29, 2017 at 19:45
  • 2
    @Brent The OP asked for both - "'n' spaces (or any string)", and then goes on to demonstrate their intent with a single period as the string. English is not many people's first language so you sometimes need to guess their exact requirements and when analysed, the question is really asking how to do this with a single character. I'm sorry you found my answer unhelpful enough you needed to down vote it.
    – camh
    Commented Dec 30, 2017 at 7:10
  • 1
    @camh The question title asks how to repeat a string. Most people landed on this question for that reason, not to repeat just a character. Also, if you are at a stage where you feel like you need to guess an OP's requirements, it is generally much better to ask for clarifications.
    – Kröw
    Commented Feb 24, 2023 at 8:35
  • 1
    At least @camh wrote helpful and partially correct answer (when the length of the string is 1). The answer is much more helpful than other comments which do not try to solve OP's question at all but just trying to point out mistakes of someone who tried to help.
    – JSong
    Commented May 2 at 4:16
23

For the purposes of the example provided by the OP std::string's ctor is sufficient: std::string(5, '.'). However, if anybody is looking for a function to repeat std::string multiple times:

std::string repeat(const std::string& input, unsigned num)
{
    std::string ret;
    ret.reserve(input.size() * num);
    while (num--)
        ret += input;
    return ret;
}
15

As Commodore Jaeger alluded to, I don't think any of the other answers actually answer this question; the question asks how to repeat a string, not a character.

While the answer given by Commodore is correct, it is quite inefficient. Here is a faster implementation, the idea is to minimise copying operations and memory allocations by first exponentially growing the string:

#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 an 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 around 10x faster than the implementation given by Commodore, and about 2x faster than a naive 'append n - 1 times' solution.

8
  • 1
    Your implementation does not 'minimize copying'. Mind that the += within your for loop internally also has a loop of some sort which does str.size() iterations. str.size() grows in each outer loop iteration, so after each outer iteration the inner loop has to do more iterations. Your and the naive 'copy n times' implementation in total both copy n * period characters. Your implementation does only one memory allocation because of the initial reserve. I guess you profiled your implementation with a rather small str and a big n, but not also with big str and a small n. Commented Jan 20, 2016 at 21:02
  • 3
    It was a comment stating that I don't believe your claim that your solution is much better in terms of efficiency than the naive solution. In my measurements, compared to the naive solution, your code is faster with small strings and many repetitions, but slower with long strings and few repetitions. Could you provide links explaining in more detail the variety of reasons why copying a few big blocks has a higher performance than copying many small blocks? I can think of branch prediction. Regarding CPU cache I am unsure which variant is preferred. Commented Jan 21, 2016 at 7:42
  • 1
    @FlorianKaufmann: On x86, rep movsb is one of the most efficient ways to copy, at least for medium to large copies. Its micro-coded implementation has some near-constant startup overhead (on both AMD and Intel), e.g. on Sandybridge, ~15 to 40 cycles, plus 4 cycles per 64B cache line (best case). For small copies, an SSE loop is best because it doesn't have the startup overhead. But then it's subject to branch mispredicts. Commented May 1, 2016 at 2:46
  • 2
    This is inefficient code. When n==0, why bother str.clear and shrink, just return a new empty std::string{} with RVO
    – caoanan
    Commented Nov 26, 2021 at 3:45
  • 1
    @oligofren: I forget what my point was 7 years go. It seems a bit off topic for this comment thread. libc memcpy uses SSE (or AVX) loops. Compilers generally don't inline looping SIMD code for memcpy, as that could get bloated, but a few extra instructions to set up and call memcpy doesn't add much overhead. That dynamic-library call involves a function pointer, which is how (on glibc at least) it can dispatch to a version that uses AVX or AVX-512 depending on CPU support. Commented Apr 25, 2023 at 14:18
13

I know this is an old question, but I was looking to do the same thing and have found what I think is a simpler solution. It appears that cout has this function built in with cout.fill(), see the link for a 'full' explanation

http://www.java-samples.com/showtutorial.php?tutorialid=458

cout.width(11);
cout.fill('.');
cout << "lolcat" << endl;

outputs

.....lolcat
2
  • 7
    only dots: change last line to... cout << "" << endl;
    – musefan
    Commented Jan 11, 2012 at 11:11
  • Could do the same with chaining: cout << setfill('.') << setw(11) << "" << endl;.
    – Adrian
    Commented Nov 7, 2022 at 19:11
10

You can use a C++ function for doing this:

 std::string repeat(const std::string& input, size_t num)
 {
    std::ostringstream os;
    std::fill_n(std::ostream_iterator<std::string>(os), num, input);
    return os.str();
 }
0
6

You should write your own stream manipulator

cout << multi(5) << "whatever" << "lolcat";
1
  • 23
    writing a stream manipulator is a very complicated way of doing something very simple!
    – Zero
    Commented Dec 22, 2014 at 3:39
5

Here's an example of the string "abc" repeated 3 times:

#include <iostream>
#include <sstream>
#include <algorithm>
#include <string>
#include <iterator>

using namespace std;

int main() {
    ostringstream repeated;
    fill_n(ostream_iterator<string>(repeated), 3, string("abc"));
    cout << "repeated: " << repeated.str() << endl;  // repeated: abcabcabc
    return 0;
}
3

There is another way to do this with the ranges library:

#include <string>
#include <range/v3/all.hpp>

std::string repeat(const std::string& input, size_t num)
{
    return ranges::views::repeat_n(input, num) | ranges::views::join(std::string{""}) | ranges::to<std::string>();
}

I tried to do the same with std::ranges but the support for this seems to be incomplete for all compilers (that are available on godbolt), which is why we currently still use range-v3 at work.

https://godbolt.org/z/cajYd6nWe

2

@Daniel provided an implementation that is significantly faster than other answers in its primary execution branch (where n > 1 and str is not empty). However, the corner cases are handled much more inefficiently than they could be.

This implementation corrects those issues:

#include <string>
#include <cstddef>

std::string repeat(size_t n, const std::string& str) {
    if (n == 0 || str.empty()) return {};
    if (n == 1) return str;
    const auto period = str.size();
    if (period == 1) return std::string(n, str.front());

    std::string ret(str);
    ret.reserve(period * n);
    std::size_t m {2};
    for (; m < n; m *= 2) ret += ret;
    ret.append(ret.c_str(), (n - (m / 2)) * period);
    return ret;
}

A benchmark comparison of the two implementations on quick-bench.com shows the following differences in these corner cases. Clang 13.0 is the first number and GCC 10.3 is the second. -O3 optimization in all cases.

  • For n == 0, this implementation is (9x / 11x) faster.
  • For str.empty() == true, it is (2.4x / 3.4x) faster.
  • For n == 1 and str.size() > 1, it is (2.1x / 1.4x) faster.
  • And for str.size() == 1, it is (1.3x / 1.2x) faster.

The problem with the original implementation boils down to passing str into the function by value. This invokes a copy of str on every call to repeat that is unnecessary in some of the corner cases; especially when n == 0.

0

Building/optimizing previous answers:

std::string repeat(const std::string& input, uint32_t num) {
    std::string ret;
    ret.reserve(input.size() * num);
    for (int8_t index=31; index>=0; index--) if (num >> index) {
        ret += ret;
        if ((num >> index)%2) {
            ret += input;
        }   
    }
    return ret;
}

Rather than copying the string num times, it doubles the string (or doubles + 1). So, copying 10 times only does 4 updates rather than 10; 65535 does 16 updates, rather than 65535.

repeat("x", 1766406154) takes 1.7 seconds to generate a 1.7GB string on my computer - any repeat large than that runs out of memory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.