What is the string.repeat() method in Rust?
Overview
In Rust, the repeat() method of a string is used to repeat a string a specified number of times. It will repeat the string for the number of times specified.
Syntax
string.repeat(n)
Syntax for repeating a string in Rust
Parameters
string: This is the string we want to repeat a number of times.
n: This is the number of times we want to repeat the string.
Return value
This method returns a string repeated many times.
Example
fn main() {// create some stringslet str1 = "hello";let str2 = "welcome";let str3 = "to";let str4 = "edpresso";// print the strings for a repeated number of timesprintln!("{}", str1.repeat(3));println!("{}", str2.repeat(1));println!("{}", str3.repeat(5));println!("{}", str4.repeat(4));}
Explanation
- Line 3–6: We create some strings.
- Line 9–12: We use the
repeat()method to repeat the strings a particular number of times. Next, we print the results to the console.