Start learning free

LESSON 60 OF 679 · STRINGS I

Accessing characters in Rust

Lesson

Each character in a string has a numbered position known as its index. We access a character by referring to its index number.

Strings use zero-based indexing, so the first character in a string has an index of 0, the second character has an index of 1, etc.

Rust can't index a string with a single integer, so we first collect its characters into a vector of char and then use bracket notation ([]) with the index after the name of the vector. (In the tutorial we'll instead slice one byte, like &fruit[0..1], which is safe for plain ASCII text.)

let message = "Hello world!";
let chars: Vec<char> = message.chars().collect();

println!("{}", chars[0]); // Output: H
println!("{}", chars[1]); // Output: e
println!("{}", chars[6]); // Output: w

Whitespaces have indices:

Note that every character inside the quotes (including whitespaces) is part of the string and has its own index. For example, in string "Hello world!", the whitespace is placed on index 5.


Assignment
Follow the Coding Tutorial and let's access some characters!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check