Add method str::repeat(self, usize) -> String

It is relatively simple to repeat a string n times:
`(0..n).map(|_| s).collect::<String>()`. It becomes slightly more
complicated to do it “right” (sizing the allocation up front), which
warrants a method that does it for us.

This method is useful in writing testcases, or when generating text.
`format!()` can be used to repeat single characters, but not repeating
strings like this.
This commit is contained in:
Ulrik Sverdrup 2016-09-24 19:35:24 +02:00
parent a5dbf8a0f8
commit 2b7222d3ec
3 changed files with 28 additions and 0 deletions

View file

@ -1746,4 +1746,24 @@ impl str {
String::from_utf8_unchecked(slice.into_vec())
}
}
/// Create a [`String`] by repeating a string `n` times.
///
/// [`String`]: string/struct.String.html
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(repeat_str)]
///
/// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
/// ```
#[unstable(feature = "repeat_str", issue = "37079")]
pub fn repeat(&self, n: usize) -> String {
let mut s = String::with_capacity(self.len() * n);
s.extend((0..n).map(|_| self));
s
}
}

View file

@ -19,6 +19,7 @@
#![feature(enumset)]
#![feature(pattern)]
#![feature(rand)]
#![feature(repeat_str)]
#![feature(step_by)]
#![feature(str_escape)]
#![feature(test)]

View file

@ -1272,6 +1272,13 @@ fn test_cow_from() {
}
}
#[test]
fn test_repeat() {
assert_eq!("".repeat(3), "");
assert_eq!("abc".repeat(0), "");
assert_eq!("α".repeat(3), "ααα");
}
mod pattern {
use std::str::pattern::Pattern;
use std::str::pattern::{Searcher, ReverseSearcher};