[英]Repeat a string stored in a variable x number of times
I am looking to print a string stored in a variable multiple times. 我想多次打印存储在变量中的字符串。 In python I would be able to do this simply by using something like this:
在python中,我可以简单地通过使用以下代码来做到这一点:
l1= "*" * width l2= "*" + (" " * (width-2)) + "*\\n" l3= l2 * ((height-4)/2)
Where height and width are provided as inputs by the user. 用户提供高度和宽度作为输入的地方。 Ultimately there are several other lines of code like this that will print a rectangle of *s.
最终,还有其他几行这样的代码行将打印一个* s矩形。
Is there a simple way to do this in C++? 有没有一种简单的方法可以在C ++中做到这一点?
I tried using l2= std::string((height-4)/2, l1);
我尝试使用
l2= std::string((height-4)/2, l1);
, but this causes an error since C++ want a string in place of L2. ,但这会导致错误,因为C ++希望使用字符串代替L2。 (l1 is formatted using the
std::string()
function and works properly. (l1使用
std::string()
函数格式化,并且可以正常工作。
Any help is greatly appreciated. 任何帮助是极大的赞赏。
std::string
has a constructor that takes a character and a repetition argument, which you can use directly to generate the top and bottom lines, something like: std::string
具有一个接受字符和重复参数的构造函数,您可以将其直接用于生成顶行和底行,例如:
std::string l1 = std::string(width, '*') + "\n";
Likewise, the "middle" lines could be generated something like this: 同样,“中间”行可能会生成如下所示:
std::string l2 = "*" + std::string(width-2, ' ') + "*\n";
As for putting the pieces together into a square goes, I'd probably use std::generate_n
to generate the middle lines, so the code would look something like this: 至于将各个部分组合成一个正方形,我可能会使用
std::generate_n
来生成中间行,因此代码看起来像这样:
auto l1 = std::string(width, '*') + "\n";
std::cout << l1;
std::generate_n(std::ostream_iterator<std::string>(std::cout),
height-2,
[=] {return "*" + std::string(width - 2, ' ') + "*\n"; });
std::cout << l1;
If you really need the result in a string instead of being written to cout
, you can substitute a ostringstream
in place of cout
, and write to it, then use its str()
member to get the content as an std::string
. 如果确实需要结果而不是写入到
cout
中的字符串,则可以用ostringstream
代替cout
并写入,然后使用其str()
成员以std::string
的形式获取内容。
You could create a simple helper function to perform the task if you wanted: 如果需要,您可以创建一个简单的辅助函数来执行任务:
Example: 例:
string stringMultiplier(string startString, int multiplier){
string endString = startString;
for (int i=1; i<multiplier; i++){
endString = endString + startString;
}
return endString;
}
int main()
{
cout << stringMultiplier("*",4) << endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.