Is there a method like JavaScript’s substr in Rust?

For characters, you can use s.chars().skip(pos).take(len):

fn main() {
    let s = "Hello, world!";
    let ss: String = s.chars().skip(7).take(5).collect();
    println!("{}", ss);
}

Beware of the definition of Unicode characters though.

For bytes, you can use the slice syntax:

fn main() {
    let s = b"Hello, world!";
    let ss = &s[7..12];
    println!("{:?}", ss);
}

Leave a Comment