Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Rust Dictionary

  1. Home
  2. Rust Dictionary
  3. String::replace() / split() / trim()

String::replace() / split() / trim()

Rust strings provide useful methods such as replace() (substitution), split() (splitting), and trim() (whitespace removal). These methods do not modify the original string — they return a new value instead.

Syntax

let s = "  Hello, World!  ";

// Remove leading and trailing whitespace.
let trimmed = s.trim();                // "Hello, World!"
let left = s.trim_start();            // "Hello, World!  "
let right = s.trim_end();             // "  Hello, World!"

// Replace all occurrences of a substring.
let replaced = s.trim().replace("World", "Rust");  // "Hello, Rust!"

// Replace only the first n occurrences.
let s2 = "aabababa".replacen("a", "X", 2);         // "XXbababa"

// Split a string and return an iterator.
let parts: Vec<&str> = "a,b,c".split(',').collect();   // ["a", "b", "c"]

// Split on whitespace (treats consecutive whitespace as one).
let words: Vec<&str> = "hello world".split_whitespace().collect();

Method List

MethodDescription
s.trim()Returns a &str with leading and trailing whitespace (including newlines) removed.
s.trim_start()Returns a &str with leading whitespace removed.
s.trim_end()Returns a &str with trailing whitespace removed.
s.trim_matches(pattern)Removes the specified pattern from both ends of the string.
s.replace(from, to)Returns a new String with all occurrences of from replaced by to.
s.replacen(from, to, n)Replaces the first n occurrences of from with to.
s.split(pattern)Splits the string by a pattern and returns an iterator.
s.splitn(n, pattern)Splits into at most n parts and returns an iterator.
s.split_whitespace()Splits on whitespace, treating consecutive whitespace as a single delimiter, and returns an iterator.
s.lines()Splits on newlines and returns an iterator.
s.split_once(pattern)Splits at the first match into two parts and returns Option<(&str, &str)>.

Sample Code

fn main() {
    // Examples of trim methods.
    let s = "  Hello, Rust!  \n";
    println!("Original: '{}'", s);
    println!("trim: '{}'", s.trim());
    println!("trim_start: '{}'", s.trim_start());
    println!("trim_end: '{}'", s.trim_end());

    // Remove specific characters with trim_matches.
    let quoted = "***secret***";
    println!("trim_matches('*'): '{}'", quoted.trim_matches('*'));

    println!();

    // Examples of replace and replacen.
    let text = "I love cats. cats are great. cats!";
    println!("replace all: {}", text.replace("cats", "dogs"));
    println!("replacen(2): {}", text.replacen("cats", "dogs", 2));

    println!();

    // Example of split.
    let csv = "apple,banana,,cherry";
    let parts: Vec<&str> = csv.split(',').collect();
    println!("split(','):  {:?}", parts);  // Includes empty strings.

    // Filtering out empty elements.
    let filtered: Vec<&str> = csv.split(',').filter(|s| !s.is_empty()).collect();
    println!("filtered: {:?}", filtered);

    // split_whitespace: treats consecutive whitespace as one delimiter.
    let sentence = "  Hello   World   Rust  ";
    let words: Vec<&str> = sentence.split_whitespace().collect();
    println!("split_whitespace: {:?}", words);

    // lines: split a multi-line string.
    let multiline = "line1\nline2\nline3";
    for line in multiline.lines() {
        println!("line: {}", line);
    }

    println!();

    // split_once: split at the first match only.
    let key_value = "name=Alice=Bob";  // Split only at the first '='.
    if let Some((key, value)) = key_value.split_once('=') {
        println!("key: {}, value: {}", key, value);
    }

    // Practical example: parse a single CSV row.
    let row = "2026,03,05,Tokyo";
    let fields: Vec<&str> = row.split(',').collect();
    println!("\nyear={}, month={}, day={}, location={}", fields[0], fields[1], fields[2], fields[3]);
}

Notes

All of these methods leave the original string unchanged and return a new value. Because split() returns an iterator, it avoids allocating memory until you actually need the results. To collect the results into a Vec, append .collect() at the end.

Rust string operations are designed with UTF-8 in mind. The pattern argument for split() can be a string slice, a char, or a closure.

When the pattern appears consecutively, split() includes empty strings in the result. For example, "a,,b".split(',') produces ["a", "", "b"]. To exclude empty elements, combine it with .filter(|s| !s.is_empty()).

For iterating over and converting characters, see String::chars() / bytes() / parse().

If you find any errors or copyright issues, please .