Start learning free

LESSON 60 OF 348 · STRINGS I

String Slicing in Rust 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:

&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.


STEP 1 OF 3
    Ctrl + Enter to check

    String Slicing in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free