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

前端 未结 7 1218
天命终不由人
天命终不由人 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 10:54

    You can use the as_str method on the Chars iterator to get back a &str slice after you have stepped on the iterator. So to skip the first start chars, you can call

    let s = "Some text to slice into";
    let mut iter = s.chars();
    iter.by_ref().nth(start); // eat up start values
    let slice = iter.as_str(); // get back a slice of the rest of the iterator
    

    Now if you also want to limit the length, you first need to figure out the byte-position of the length character:

    let end_pos = slice.char_indices().nth(length).map(|(n, _)| n).unwrap_or(0);
    let substr = &slice[..end_pos];
    

    This might feel a little roundabout, but Rust is not hiding anything from you that might take up CPU cycles. That said, I wonder why there's no crate yet that offers a substr method.

提交回复
热议问题