用整数乘法重复字符串 [英] Repeat string with integer multiplication
本文介绍了用整数乘法重复字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种简单的方法可以在 Rust 中执行以下操作(来自 Python)?
Is there an easy way to do the following (from Python) in Rust?
<代码>>>>打印(重复"* 4)重复重复重复重复
我开始学习这门语言,似乎 String
并没有覆盖 Mul
,而且我在任何地方都找不到任何关于紧凑方式的讨论这样做(除了地图或循环).
I'm starting to learn the language, and it seems String
doesn't override Mul
, and I can't find any discussion anywhere on a compact way of doing this (other than a map or loop).
推荐答案
Rust 1.16+
str::repeat
现在可用:
fn main() {
let repeated = "Repeat".repeat(4);
println!("{}", repeated);
}
Rust 1.0+
您可以使用 iter::repeat
:
use std::iter;
fn main() {
let repeated: String = iter::repeat("Repeat").take(4).collect();
println!("{}", repeated);
}
这也有一个更通用的好处——它创建了一个无限重复的任何类型的可克隆迭代器.
This also has the benefit of being more generic — it creates an infinitely repeating iterator of any type that is cloneable.
这篇关于用整数乘法重复字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文