Best way to create a string containing multiple copies of another string

c++, string

Solution

I don't see a problem with looping, just make sure you do a reserve first:

std::string MakeDuplicate( const std::string& str, int x )
{
    std::string newstr;
    newstr.reserve(str.length()*x); // prevents multiple reallocations

    // loop...

    return newstr;
}

Problem

I want to create a function that will take a string and an integer as parameters and return a string that contains the string parameter repeated the given number of times. For example: ``` std::string MakeDuplicate( const std::string& str, int x ) { ... } ``` Calling `MakeDuplicate( "abc", 3 );` would return `"abcabcabc"`. I know I can do this just by looping x number of times but I'm sure there must be a better way.

Original source