Strings

Using String and &str types in Rust.

Intermediate⏱️ 35 min📚 Prerequisites: 1

Strings

In Rust, there are two main string types:

  • String: Mutable, owned string (stored on heap)
  • &str: Immutable string slice (reference)

Creating a String

RUST
let mut s = String::new();
let s = String::from("hello");
let s = "hello".to_string();

String Concatenation

RUST
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2;  // s1 is moved, s2 is reference

format! Macro

RUST
let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");

let s = format!("{}-{}-{}", s1, s2, s3);

String Indexing

In Rust, you CANNOT directly index a string:

RUST
let s = String::from("hello");
// let h = s[0];  // ERROR!

This is because strings are stored in UTF-8 bytes, and one character can be multiple bytes.

String Slices

RUST
let hello = "Здравствуй";
let s = &hello[0..4];  // Within UTF-8 character boundaries!

Iteration

RUST
for c in "नमस्ते".chars() {
    println!("{}", c);
}

for b in "नमस्ते".bytes() {
    println!("{}", b);
}

Code Examples

Basic String

Creating and modifying a String

RUST
fn main() {
    let mut s = String::new();
    s.push_str("hello");
    s.push(' ');
    s.push_str("world");
    println!("{}", s);
    let s2 = String::from("hello");
    println!("{}", s2);
}

Explanation:

String::new() creates an empty string. push_str() adds a string, push() adds a character. String::from() creates a string from a literal.

String Concatenation

Combining strings

RUST
fn main() {
    let s1 = String::from("Hello, ");
    let s2 = String::from("world!");
    let s3 = s1 + &s2;
    println!("{}", s3);
    let s4 = String::from("Hello");
    let s5 = String::from("world");
    let s6 = format!("{}, {}!", s4, s5);
    println!("{}", s6);
    println!("{}", s4);
}

Explanation:

The + operator moves the first string and takes the second as a reference. The format! macro doesn't move, both strings remain usable.

String Iteration

Iterating through string characters

RUST
fn main() {
    let s = String::from("नमस्ते");
    println!("Characters:");
    for c in s.chars() {
        println!("{}", c);
    }
    println!("\nBytes:");
    for b in s.bytes() {
        println!("{}", b);
    }
}

Explanation:

The chars() method returns characters (grapheme clusters), the bytes() method returns bytes. For UTF-8 strings, one character can be multiple bytes.

Exercises

String Operations

Create a String, add texts to it, and print it!

Easy

Starter Code:

RUST
fn main() {
}