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()

Since: Rust 1.0(2015)

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 by whitespace (treats consecutive whitespace as one).
let words: Vec<&str> = "hello world".split_whitespace().collect();

Method Reference

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.
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 by pattern and returns an iterator.
s.splitn(n, pattern)Splits into at most n parts and returns an iterator.
s.split_whitespace()Splits by whitespace (handles consecutive whitespace) and returns an iterator.
s.lines()Splits by newline and returns an iterator.
s.split_once(pattern)Splits at the first match into two parts and returns Option<(&str, &str)>.

Sample Code

sample_string_replace_split_trim.rs
fn main() {
    // 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 a specific character with trim_matches.
    let quoted = "***secret***";
    println!("trim_matches('*'): '{}'", quoted.trim_matches('*'));

    println!();

    // replace / replacen examples.
    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!();

    // split examples.
    let csv = "kiryu,majima,,nishiki";
    let parts: Vec<&str> = csv.split(',').collect();
    println!("split(','):  {:?}", parts); // includes empty strings

    // Exclude 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 by newline.
    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=Kiryu Kazuma=Majima Goro"; // Split only at the first =.
    if let Some((key, value)) = key_value.split_once('=') {
        println!("key: {}, value: {}", key, value);
    }

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

Compile with the following command:

rustc string_replace_split_trim.rs
./string_replace_split_trim
original: '  Hello, Rust!
'
trim: 'Hello, Rust!'
trim_start: 'Hello, Rust!
'
trim_end: '  Hello, Rust!'
trim_matches('*'): 'secret'

replace all: I love dogs. dogs are great. dogs!
replacen(2): I love dogs. dogs are great. cats!

split(','):  ["kiryu", "majima", "", "nishiki"]
filtered: ["kiryu", "majima", "nishiki"]
split_whitespace: ["Hello", "World", "Rust"]
line: line1
line: line2
line: line3

key: name, value: Kiryu Kazuma=Majima Goro

year=2026, month=03, day=05, place=Tokyo

Common Mistakes

Mistake 1: Unexpected empty-string elements from split()

split() generates empty strings when the pattern appears consecutively or at the start or end of the string. This can result in unintended empty elements in the output.

string_split_mistake1.rs
fn main() {
    // Consecutive commas produce empty strings.
    let csv = "a,,b,c,";
    let parts: Vec<&str> = csv.split(',').collect();
    println!("{:?}", parts); // ["a", "", "b", "c", ""] — two empty strings included
    println!("count: {}", parts.len()); // 5

    // Use filter to exclude empty elements.
    let clean: Vec<&str> = csv.split(',').filter(|s| !s.is_empty()).collect();
    println!("{:?}", clean); // ["a", "b", "c"]
}

Compile with the following command:

rustc string_split_mistake1.rs
./string_split_mistake1
["a", "", "b", "c", ""]
count: 5
["a", "b", "c"]

Mistake 2: Assuming trim() does not remove certain whitespace characters

trim() removes Unicode whitespace characters including regular half-width spaces (U+0020), newlines, and tabs. The fullwidth space (U+3000, ideographic space) is also treated as a Unicode whitespace character and will be removed by trim(). However, custom or non-standard space-like characters may not be removed.

string_trim_note.rs
fn main() {
    // Half-width spaces are removed by trim.
    let s1 = "  hello  ";
    println!("'{}'", s1.trim()); // 'hello'

    // The fullwidth space (U+3000) is also removed by trim.
    let s2 = "\u{3000}hello\u{3000}";
    println!("'{}'", s2.trim()); // 'hello'

    // Newlines and tabs are removed as well.
    let s3 = "\t\nhello\r\n";
    println!("'{}'", s3.trim()); // 'hello'

    // trim_matches() removes only a specific pattern.
    let s4 = "***hello***";
    println!("'{}'", s4.trim_matches('*')); // 'hello'
}

Compile with the following command:

rustc string_trim_note.rs
./string_trim_note
'hello'
'hello'
'hello'
'hello'

Overview

All of these methods leave the original string unchanged and return a new value. split() returns an iterator, so memory is conserved if you don't immediately consume it. Append .collect() when you need a Vec.

Rust's string operations are designed with UTF-8 awareness. The pattern argument to split() can be a string, a char, or a closure.

split() returns empty-string elements when the pattern appears consecutively. For example, "a,,b".split(',') yields ["a", "", "b"]. Use .filter(|s| !s.is_empty()) to exclude empty elements.

For character-level iteration and conversion, see String::chars() / bytes() / parse().

If you find any errors or copyright issues, please .