November 2017
Intermediate to advanced
264 pages
5h 45m
English
Back in the first section of this chapter we saw that the sequence of characters in a string is given by the function chars(). Doesn't this look like an array to you? A string is backed up by an array if we look at the memory allocation of its characters; it is stored as a vector of bytes Vec<u8>.
That means we can also take a slice of type &str from a string:
let location = "Middle-Earth";
let part = &location[7..12];
println!("{}", part); // Earth
We can collect the characters of a string slice into a vector and sort them as follows:
let magician = "Merlin";
let mut chars: Vec<char> = magician.chars().collect();
chars.sort();
for c in chars.iter() {
print!("{} ", c);
}
This prints out the following output:
M e i l ...
Read now
Unlock full access