创建包含另一个字符串的多个副本的字符串的最佳方法 [英] Best way to create a string containing multiple copies of another 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.
例如:
std::string MakeDuplicate( const std::string& str, int x )
{
...
}
调用 MakeDuplicate("abc",3);
会返回"abcabcabc"
.
我知道我可以通过循环x次来做到这一点,但是我敢肯定必须有更好的方法.
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;
}
这篇关于创建包含另一个字符串的多个副本的字符串的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文