Start learning free

LESSON 62 OF 348 · STRINGS I

String Length in Rust in Rust

Lesson

We can get the length of a string using the .len() method like this:

let mut message = String::from("Hello world");

// Printing the length:
println!("{}", message.len()); // Output: 11

// Changing the message:
message += "!";

// Printing the new length:
println!("{}", message.len()); // Output: 12

Accessing characters from the end:

The length is useful for accessing characters from the end of a string.

Because strings are 0-indexed, the index of the last character is length - 1:

let message = String::from("Hello world");
let length = message.len();

// Printing the last character:
println!("{}", &message[length - 1..length]); // Output: d

// Printing the second to last character:
println!("{}", &message[length - 2..length - 1]); // Output: l

In general, if you want the nth last character, you use &message[length - n..length - n + 1].


Slicing characters from the end:

The length is also useful for slicing some characters from the end of a string:

let message = String::from("Hello world");
let length = message.len();

// Slicing last 4 characters:
let last_chars = &message[length - 4..];
println!("{}", last_chars); // Output: orld

// Slicing last 7 characters:
let last_chars = &message[length - 7..];
println!("{}", last_chars); // Output: o world

In general, if you want the last n characters, you use &message[length - n..].


Assignment
Follow the Coding Tutorial and let's practice with string length!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    String Length 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