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