Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

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.

like image 974
Richard Avatar asked Jan 11 '10 15:01

Richard


2 Answers

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;
}
like image 84
luke Avatar answered Oct 03 '22 08:10

luke


At some point it will have to be a loop. You may be able to hide the looping in some fancy language idiom, but ultimately you're going to have to loop.

like image 38
John Weldon Avatar answered Oct 03 '22 08:10

John Weldon