Start learning free

LESSON 61 OF 679 · STRINGS I

String Slicing in Rust

Lesson

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 (the indexes are byte positions, which match characters for plain ASCII text):

&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 borrows a read-only view (a &str) of the part you asked for.


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.


STEP 1 OF 3
    Ctrl + Enter to check