Storing UTF-8 Encoded Text with Strings

In this chapter, we'll explore work with text using mana's string type.

Storing UTF-8 Encoded Text with Strings

Strings are collections of characters. Mana has two main string types:

  • str — String slice, usually seen as &str
  • string — Growable, heap-allocated string

Creating Strings

// Empty string
let mut s = String::new()
 
// From string literal
let s = String::from("initial contents")
let s = "initial contents".to_string()

Updating Strings

let mut s = String::from("foo")
s.push_str("bar")  // Append string slice
s.push('!')        // Append character

Concatenation:

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

For complex concatenation, use variadic functions:

let s1 = String::from("tic")
let s2 = String::from("tac")
let s3 = String::from("toe")
 
let s = format(s1, "-", s2, "-", s3)  // "tic-tac-toe"

String Methods

let s = "  Hello, World!  "
 
s.len()                // Length in bytes
s.is_empty()           // Check if empty
s.trim()               // Remove whitespace
s.to_uppercase()       // "  HELLO, WORLD!  "
s.to_lowercase()       // "  hello, world!  "
s.contains("World")    // true
s.replace("World", "Mana")  // "  Hello, Mana!  "
s.split(",")           // Iterator over parts

Iterating Over Strings

By characters:

for c in "hello".chars() {
    println(c)
}

By bytes:

for b in "hello".bytes() {
    println(b)
}

String Slices

Access portions of a string:

let s = String::from("hello world")
let hello = &s[0..5]
let world = &s[6..11]

Be careful: slicing at invalid byte boundaries causes a panic.

Continue to Hash Maps.