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 it?
str.substr(start[, length])
The closest is probably slice_unchecked
but it uses byte offsets instead of character indexes and is marked unsafe
.
For
my_string.substring(start, len)
-like syntax, you can write a custom trait:This code performs both substring-ing and string-slicing, without panicking nor allocating:
You can use the
as_str
method on theChars
iterator to get back a&str
slice after you have stepped on the iterator. So to skip the firststart
chars, you can callNow if you also want to limit the length, you first need to figure out the byte-position of the
length
character: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.For characters, you can use
s.chars().skip(pos).take(len)
:Beware of the definition of Unicode characters though.
For bytes, you can use the slice syntax: