Rust String Methods
Rust's String
and &str
types provide many useful methods similar to Python's string methods. Below is a list of common operations and their equivalents in Rust.
Checking Prefix & Suffix
let s = "hello world";
assert!(s.starts_with("hello"));
assert!(s.ends_with("world"));
assert!(s.contains("lo"));
Trimming Whitespace
let s = " hello ";
assert_eq!(s.trim(), "hello");
assert_eq!(s.trim_start(), "hello ");
assert_eq!(s.trim_end(), " hello");
Modifying Case
Splitting & Joining
split
: Splits a string on a delimiter.
let s = "a,b,c";
let parts: Vec<&str> = s.split(',').collect();
assert_eq!(parts, vec!["a", "b", "c"]);
split_whitespace
: Splits by whitespace.
let s = "hello world";
let parts: Vec<&str> = s.split_whitespace().collect();
assert_eq!(parts, vec!["hello", "world"]);
splitn
: Splits a string into a maximum of N substrings.
let s = "a,b,c,d";
let parts: Vec<&str> = s.splitn(2, ',').collect();
assert_eq!(parts, vec!["a", "b,c,d"]);
join
: Joins an iterator of strings with a separator.
Replacing & Removing Characters
replace
: Replaces all occurrences of a substring.
replacen
: Replaces the first N occurrences.
trim_matches
: Trims specific characters from start and end.
trim_start_matches
: Trims specific characters from start.
Indexing & Slicing
chars
: Iterates over characters.
bytes
: Iterates over bytes.
- Slicing: Getting a substring using byte indices.
⚠ Note: Rust strings are UTF-8 encoded, so slicing must align with character boundaries.
Checking Empty or Length
is_empty
: Checks if a string is empty.
len
: Gets the length (in bytes, not characters!).
Converting Between Strings
to_string
: Converts into aString
.
String::from
: Creates aString
from a&str
.