Not only we can select a single character from a string, but we can also select a sequence of consecutive characters (e.g. substring) from a string.
To achieve this, we use a range slice like this:
&string[startIndex..endIndex];
This is called slicing a string. It returns the substring that starts at startIndex and ends just before endIndex.
Here is an example:
let language = "JavaScript";
let substring = &language[2..6];
println!("{}", substring); // Output: "vaSc"
println!("{}", language); // Output: "JavaScript"
Notice that language preserved its value. The slicing does not affect the original string. It just creates a brand new one representing the sliced substring.
If you omit the end index, the slice extracts to the end of the string:
let language = "JavaScript";
let substring = &language[4..];
println!("{}", substring); // Output: "Script"
Assignment
Follow the Coding Tutorial and let's slice some strings!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.