创建包含另一个字符串的多个副本的字符串的最佳方法

Ric*_*ard 5 c++ string

我想创建一个函数,它将一个字符串和一个整数作为参数,并返回一个包含重复给定次数的字符串参数的字符串.

例如:

std::string MakeDuplicate( const std::string& str, int x )
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

打电话MakeDuplicate( "abc", 3 );会回来"abcabcabc".

我知道我可以通过循环x次来做到这一点,但我确信必须有更好的方法.

luk*_*uke 19

我没有看到循环问题,只要确保你先保留:

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

    // loop...

    return newstr;
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*don 7

在某些时候,它必须是一个循环.你可能能够隐藏一些花哨的语言习语,但最终你将不得不循环.