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)
Syntax
fn trim(&self) -> &str fn split<P>(&self, pat: P) -> Split<P> fn replace<P>(&self, from: P, to: &str) -> String
Parameters
| Parameter | Description |
|---|---|
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
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.
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.
Related
String::push_str, format! and join· Build strings: append with push_str and push, format with format!, and join a list of strings with a separator.str::chars and char_indices· Iterate over the Unicode characters of a string (not bytes), with their byte positions when needed.- Rust Slices and Strings · tutorial