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

String operations: push_str, split, replace, trim.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

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

More Compound Types Examples