Repeat string with integer multiplication

后端 未结 2 966
旧时难觅i
旧时难觅i 2021-01-03 17:21

Is there an easy way to do the following (from Python) in Rust?

>>> print (\"Repeat\" * 4) RepeatRepeatRepeatRepeat

I\'m starting to l

2条回答
  •  花落未央
    2021-01-03 17:58

    Rust 1.16+

    str::repeat is now available:

    fn main() {
        let repeated = "Repeat".repeat(4);
        println!("{}", repeated);
    }
    

    Rust 1.0+

    You can use 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.

提交回复
热议问题