Card 1 / 12
Rust has two main string types: &str (a borrowed string slice) and String (an owned, growable string). Return the length of s in bytes — .len() counts bytes, not characters, so non-ASCII characters contribute more than one.
s |
string_length(s) |
exercises |
|---|---|---|
"hello" |
5 |
one byte per ASCII character |
"" |
0 |
empty string |
"héllo" |
6 |
é is 2 bytes in UTF-8 |
Simply call .len() on the string slice.
/// Return the length of the string
fn string_length(s: &str) -> usize {
s.len()
}Card 2 / 12
Return a new String with the characters of s in reverse order. chars() walks Unicode scalar values, not bytes, so multibyte characters survive the trip intact.