I looked at the Rust docs for String but I can\'t find a way to extract a substring.
Is there a method like JavaScript\'s substr in Rust? If not, how would you implement
For my_string.substring(start, len)
-like syntax, you can write a custom trait:
trait StringUtils {
fn substring(&self, start: usize, len: usize) -> Self;
}
impl StringUtils for String {
fn substring(&self, start: usize, len: usize) -> Self {
self.chars().skip(start).take(len).collect()
}
}
// Usage:
fn main() {
let phrase: String = "this is a string".to_string();
println!("{}", phrase.substring(5, 8)); // prints "is a str"
}