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

前端 未结 7 1098
天命终不由人
天命终不由人 2021-02-02 10:21

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

7条回答
  •  死守一世寂寞
    2021-02-02 11:02

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

提交回复
热议问题