RRust By Example
intermediateCompound Types

String Manipulation

Common string operations: concat, split, replace, trim.

String Manipulation

Common string operations: concat, split, replace, trim.

Difficulty

Intermediate

Code

rust
fn main() {
    let mut s = String::from("Hello");
    s.push_str(", world!");
    s.push('!');
    println!("{}", s);

    let parts: Vec<&str> = "a,b,c".split(',').collect();
    println!("{:?}", parts);

    let replaced = "foo bar foo".replace("foo", "baz");
    println!("{}", replaced);

    let trimmed = "  hello  ".trim();
    println!(""{}"", trimmed);
}

Explanation

This example demonstrates how to use string manipulation in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the compound-types category to build a complete understanding of this topic.

More Compound Types Examples