Strings

String and &str, common methods, formatting, characters vs bytes, and splitting text.

Runs in Zerethon IDE · Rust 1.87 Official Rust documentation ↗
main.rs
fn main() {
    let name = "Ada Lovelace";
    println!("{name} has {} characters", name.chars().count());
    println!("{} {} {}", name.to_uppercase(), name.to_lowercase(), &name[..3]);
    println!("{}|", "  padded  ".trim());
    let parts: Vec<&str> = "a,b,c".split(',').collect();
    println!("{:?} {}", parts, ["x", "y", "z"].join("-"));
    println!("{} {} {}", name.replace("Ada", "Augusta"), name.starts_with("Ada"), name.to_lowercase().contains("love"));
    println!("{:.2} {:>5} {:03}", 3.14159, 42, 7);

    let mut s = String::new();
    s.push_str("abc");
    s += "def";
    println!("{s} {}", s.len());

    let word = "héllo";
    println!("{} {}", word.len(), word.chars().count());

    let numbers: Vec<u32> = "Order 12 shipped, order 7 pending"
        .split(|c: char| !c.is_ascii_digit())
        .filter(|p| !p.is_empty())
        .map(|p| p.parse().unwrap())
        .collect();
    println!("{:?}", numbers);
}

Output

Ada Lovelace has 12 characters
ADA LOVELACE ada lovelace Ada
padded|
["a", "b", "c"] x-y-z
Augusta Lovelace true true
3.14    42 007
abcdef 6
6 5
[12, 7]
  • Strings are UTF-8. len() counts bytes; chars().count() counts characters.
  • A string cannot be indexed with s[0]. Slices like &s[..3] take byte ranges and stop the program if they cut a character in half.
  • Join pieces with format!("{a}{b}") or push_str; a + &b works but moves a.
  • There is no regular-expression library: runs have only the standard library. Use split, find, trim_matches and char methods instead.