Rust 1.99 (2024 edition) reference · Strings

Rust String and &str methods Method

Common text operations: trim, split, contains, replace, case conversion, starts_with and parse.

Rust 1.99 (2024 edition)

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

fn trim(&self) -> &str   fn split<P>(&self, pat: P) -> Split<P>   fn replace<P>(&self, from: P, to: &str) -> String

Parameters

ParameterDescription
trim / trim_start / trim_end Remove whitespace.
split / split_whitespace / lines Iterate parts.
contains / starts_with / ends_with Search.
replace / to_uppercase / to_lowercase New Strings.
parse::<T>() Convert to numbers and more.

Examples

Example 1
fn main() {
    let line = "  GET /api/orders HTTP/1.1  ";
    let parts: Vec<&str> = line.trim().split_whitespace().collect();
    println!("{parts:?}");
    println!("{} {}", line.contains("/api"), parts[1].starts_with("/api"));
    println!("{}", parts[1].replace("/", ":").to_uppercase());
}

Output

["GET", "/api/orders", "HTTP/1.1"]
true true
:API:ORDERS

Run this on your computer — see “Get Started” for setup.

split_once and parse
fn main() {
    let csv = "id,name\n1,Ana\n2,Ben";
    for row in csv.lines().skip(1) {
        if let Some((id, name)) = row.split_once(',') {
            let id: u32 = id.parse().unwrap();
            println!("{} -> {}", id * 100, name);
        }
    }
}

Output

100 -> Ana
200 -> Ben

Run this on your computer — see “Get Started” for setup.

Was this page helpful?