Sub topic 10
Searching, splitting, and trimming
This chapter covers the standard library methods that find text, cut it into pieces, and remove unwanted edges. It assumes you know the difference between &str and String, that you know strings are UTF-8 and slice by byte offset, and that you can work with Option and iterators.
The pattern argument
Most search and split methods take a pattern. A pattern is anything that can match part of a string. You can pass:
- a
&str, such as"ab", which matches that exact text - a
char, such as',' - a closure
|c: char| -> bool, which matches any character where it returnstrue - an array or slice of chars, such as
['-', '_'], which matches any one of them
Because one pattern type covers all of these, s.find('l'), s.find("l"), and s.find(char::is_whitespace) use the same method. A char pattern is usually the cheapest choice when you only need one character.
Searching
contains, starts_with, and ends_with answer yes/no questions. find and rfind return the byte offset of the first or last match as an Option<usize>.
fn main() {
let text = "héllo, wörld";
println!("{}", text.contains("wör")); // true
println!("{}", text.starts_with('h')); // true
println!("{}", text.ends_with("ld")); // true
println!("{:?}", text.find('l')); // Some(3)
println!("{:?}", text.rfind('l')); // Some(12)
println!("{:?}", text.find("zzz")); // None
println!("{:?}", text.find(|c: char| c.is_ascii_punctuation())); // Some(6)
if let Some(i) = text.find(',') {
println!("{:?} | {:?}", &text[..i], &text[i + 1..]);
}
}find('l') returns Some(3), not Some(2), because é occupies bytes 1 and 2. Offsets from find always land on a character boundary, so using them to slice never panics. That makes find plus slicing the safe way to cut at a known place. Add c.len_utf8() instead of 1 if the match could be a non-ASCII character.
Two related methods return every match instead of the first:
matches(pat)yields each matching substring. It is mostly useful with closures, for example counting digits.match_indices(pat)yields(offset, &str)pairs.
fn main() {
let s = "a1b22c333";
let digits = s.matches(|c: char| c.is_ascii_digit()).count();
println!("{digits}"); // 6
let found: Vec<(usize, &str)> = s.match_indices("2").collect();
println!("{:?}", found); // [(3, "2"), (4, "2")]
}Splitting
split cuts a string at every match and returns an iterator of &str slices. Nothing is copied. Each piece borrows from the original string.
fn main() {
let csv = "a,b,,c";
println!("{:?}", csv.split(',').collect::<Vec<_>>()); // ["a", "b", "", "c"]
println!("{:?}", csv.splitn(2, ',').collect::<Vec<_>>()); // ["a", "b,,c"]
println!("{:?}", csv.rsplitn(2, ',').collect::<Vec<_>>()); // ["c", "a,b,"]
println!("{:?}", "a;b;".split(';').collect::<Vec<_>>()); // ["a", "b", ""]
println!("{:?}", "a;b;".split_terminator(';').collect::<Vec<_>>()); // ["a", "b"]
println!("{:?}", "x-y_z".split(['-', '_']).collect::<Vec<_>>()); // ["x", "y", "z"]
}Note the behavior at the edges:
- Two adjacent separators produce an empty string between them.
- A separator at the very end produces a trailing empty string.
split_terminatortreats the separator as a terminator and drops that final empty piece.splitn(n, pat)returns at mostnpieces, and the last piece holds the unsplit remainder.rsplitndoes the same from the right.
Whitespace and lines
For human text, do not use split(' '). It creates empty pieces for runs of spaces and ignores tabs and newlines. Use split_whitespace, which splits on any Unicode whitespace and skips empty pieces.
fn main() {
let spaced = " one two\tthree\n";
println!("{:?}", spaced.split(' ').collect::<Vec<_>>());
// ["", "", "one", "", "", "two\tthree\n"]
println!("{:?}", spaced.split_whitespace().collect::<Vec<_>>());
// ["one", "two", "three"]
let text = "one\r\ntwo\n\nthree\n";
println!("{:?}", text.lines().collect::<Vec<_>>());
// ["one", "two", "", "three"]
}lines accepts both \n and \r\n endings and removes them. It does not yield an empty last line when the text ends in a newline. A lone \r does not end a line.
Splitting once
When the text has the form key=value, split_once is clearer than split plus indexing. It returns Option<(&str, &str)> and splits at the first match. rsplit_once splits at the last match.
fn main() {
let s = "key=value=more";
println!("{:?}", s.split_once('=')); // Some(("key", "value=more"))
println!("{:?}", s.rsplit_once('=')); // Some(("key=value", "more"))
println!("{:?}", "novalue".split_once('=')); // None
}The Option forces you to handle input with no separator. Indexing into a Vec from split would panic on the same input.
Trimming
Trimming returns a subslice with unwanted characters removed from the edges. It never modifies the original and never allocates.
| Method | Effect |
|---|---|
| `trim()` | Removes Unicode whitespace from both ends |
| `trim_start()`, `trim_end()` | Removes whitespace from one end |
| `trim_matches(pat)` | Removes every leading and trailing match of a char-like pattern |
| `trim_start_matches(pat)`, `trim_end_matches(pat)` | Removes repeated matches from one end |
| `strip_prefix(pat)`, `strip_suffix(pat)` | Removes one match, and returns `None` if there is no match |
fn main() {
println!("{:?}", " \t hi \n".trim()); // "hi"
println!("{:?}", "xxhixx".trim_matches('x')); // "hi"
println!("{:?}", "--hi!!".trim_matches(|c: char| !c.is_alphanumeric())); // "hi"
println!("{:?}", "ababc".trim_start_matches("ab")); // "c"
println!("{:?}", "ababc".strip_prefix("ab")); // Some("abc")
println!("{:?}", "ababc".strip_suffix("zz")); // None
}The difference between trim_start_matches and strip_prefix matters in practice. The first removes the text as many times as it repeats and always returns a string. The second removes it at most once and tells you whether it was there. Use strip_prefix when you are parsing something like "--verbose" and want to branch on whether the prefix existed.
Choosing a method
Borrowed results and lifetimes
Every piece returned by these methods is a &str tied to the source string. Returning one from a function is fine if the signature says so. Lifetime elision connects the output to the single input reference.
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
let owned = String::from(" hello world");
let word = first_word(&owned);
println!("{word}");
}The slices become invalid if the source goes away or is mutated. This code does not compile, because clear needs a mutable borrow while word still holds an immutable one:
fn main() {
let mut owned = String::from("hello world");
let word = owned.split_whitespace().next().unwrap();
owned.clear();
println!("{word}");
}If you need a piece to outlive the source, convert it with to_owned() or String::from.
Putting it together
A small config parser shows the methods working together. It trims the line, skips blanks and comments, splits once on =, and parses the value.
fn parse_line(line: &str) -> Option<(&str, i32)> {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
return None;
}
let (key, value) = line.split_once('=')?;
let n = value.trim().parse().ok()?;
Some((key.trim(), n))
}
fn main() {
let input = "# settings\n port = 8080 \nbad\nretries=3\n";
for line in input.lines() {
println!("{:?}", parse_line(line));
}
}This prints None, Some(("port", 8080)), None, and Some(("retries", 3)). The returned key is a slice of input, so the parser allocates nothing.
Common errors
- Using
split(' ')on text that can contain tabs, newlines, or repeated spaces. Usesplit_whitespace. - Forgetting the empty strings from
splitwith adjacent or trailing separators. Filter them with.filter(|p| !p.is_empty())or usesplit_terminator. - Treating the result of
findas a character index. It is a byte offset. - Passing
&strtotrim_matches. Usetrim_start_matchesandtrim_end_matches. - Assuming
trimremoves only ASCII whitespace. It removes all Unicode whitespace, including non-breaking spaces. To remove only certain characters, usetrim_matcheswith an explicit pattern. - Holding slices across a mutation of the source
String. The borrow checker rejects this, and the fix is to copy the piece first.
Exercise
What does "a,,b".split(',').count() return, and how would you change the code so empty pieces are not counted?
Show answer
It returns 3, because the two adjacent commas produce an empty string between "a" and "b". To skip empty pieces, filter them out: "a,,b".split(',').filter(|p| !p.is_empty()).count() returns 2.
Exercise
Given let arg = "--name=Ferris";, write code that extracts "name" and "Ferris" as &str values, and returns None if the argument does not start with -- or has no =.
Show answer
Use strip_prefix and split_once with the ? operator in a function returning Option<(&str, &str)>: fn parse(arg: &str) -> Option<(&str, &str)> { arg.strip_prefix("--")?.split_once('=') }. For the input above it returns Some(("name", "Ferris")).