Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat string with integer multiplication

Tags:

rust

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).

like image 804
Achal Dave Avatar asked Jul 04 '15 03:07

Achal Dave


People also ask

How do you multiply a string and an integer?

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.

What happens if you multiply a string by an integer?

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).

Can we multiply string and integer in C++?

You can, but even as the accepted answer implements string*int pretty much like this: DON'T.

Can we multiply string with int in Java?

No. Java does not have this feature.


1 Answers

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.

like image 152
Shepmaster Avatar answered Oct 17 '22 23:10

Shepmaster