Search code examples
stringsubstringrust

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


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 it?

str.substr(start[, length])

The closest is probably slice_unchecked but it uses byte offsets instead of character indexes and is marked unsafe.


Solution

  • 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);
    }