Start learning free

LESSON 280 OF 679 · STRINGS

Strings in Rust

Lesson

The Rust string is an object that represents a sequence of characters, each identified by one index.

Creation:

To create strings in Rust, you use double quotes like this:

let greeting = "Hello";

Accessing characters:

To access the characters in a string, you use the .chars().nth() method

The following example returns the first character of a string with the index zero:

let str = "Hello";
let ch = str.chars().nth(0).unwrap();
// ch is 'H'

Getting the length:

We can get the length of a string in bytes using the .len() method (for plain ASCII text this is the number of characters, and .chars().count() counts characters in general).

To access the last character of the string, you use the .chars().last() method:

let str = "Hello";
let ch = str.chars().last().unwrap();
// ch is 'o'

Concatenating strings via + operator:

To concatenate two or more strings, you use the format! macro or the + operator:

let name = "John";
let str = format!("Hello {}", name);

println!("{}", str); // prints "Hello John"

If you want to assemble a string piece by piece, you can use the push_str() method:

let mut greet = "Welcome".to_string();
let name = "John";
greet.push_str(" to AlgoCademy, ");
greet.push_str(name);

println!("{}", greet); // prints "Welcome to AlgoCademy, John"

String slicing

We often want to get a substring of a string. For this, we use a range slice.

&str[startIndex..endIndex] returns the substring starting from startIndex and ending just before endIndex:

let str = "JavaScript";
let substr = &str[2..6];

println!("{}", substr); // prints "vaSc"

The startIndex is a zero-based index at which the slice starts extraction.

The endIndex parameter specifies where to stop (exclusive). The number of characters extracted equals endIndex - startIndex.

If you omit the end index, the slice extracts to the end of the string:

let str = "JavaScript";
let substr = &str[4..];

println!("{}", substr); // prints "Script"

Iterating through the characters:

We can iterate through the characters of a string using a for loop and the .chars() method like this:

let my_str = "Andy";
for c in my_str.chars() {
    println!("{}", c);
}

// This will print the characters 'A', 'n', 'd' and 'y' on different lines

We can also iterate through the elements of a string using indices and a for loop like this:

let my_str = "Andy";
for (i, c) in my_str.chars().enumerate() {
    println!("{}", c);
}

// This will print the characters 'A', 'n', 'd' and 'y' on different lines

Both ways take O(n) time, where n is the length of the string we iterate on.


Assignment
Follow the Coding Tutorial and let's play with some strings.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 5
    Ctrl + Enter to check