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

前端 未结 7 1092
天命终不由人
天命终不由人 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:56

    The solution given by oli_obk does not handle last index of string slice. It can be fixed with .chain(once(s.len())).

    Here function substr implements a substring slice with error handling. If invalid index is passed to function, then a valid part of string slice is returned with Err-variant. All corner cases should be handled correctly.

    fn substr(s: &str, begin: usize, length: Option) -> Result<&str, &str> {
        use std::iter::once;
        let mut itr = s.char_indices().map(|(n, _)| n).chain(once(s.len()));
        let beg = itr.nth(begin);
        if beg.is_none() {
            return Err("");
        } else if length == Some(0) {
            return Ok("");
        }
        let end = length.map_or(Some(s.len()), |l| itr.nth(l-1));
        if let Some(end) = end {
            return Ok(&s[beg.unwrap()..end]);
        } else {
            return Err(&s[beg.unwrap()..s.len()]);
        }
    }
    let s = "abc

提交回复
热议问题