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