Is there an easy way to do the following (from Python) in Rust?
>>> print ("Repeat" * 4) RepeatRepeatRepeatRepeat
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).
To (properly) multiply an string by an integer, you split the string into characters, repeat each character a number of times equal to the integer, and then stick the characters back together. If the integer is negative, we use its absolute value in the first step, and then reverse the string.
When you multiply a string by an integer, Python returns a new string. This new string is the original string, repeated X number of times (where X is the value of the integer).
You can, but even as the accepted answer implements string*int pretty much like this: DON'T.
No. Java does not have this feature.
str::repeat
is now available:
fn main() { let repeated = "Repeat".repeat(4); println!("{}", repeated); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With