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.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With