Sub topic 10
Searching, splitting, and trimming
This chapter assumes you know ownership and borrowing, Option and Result, and that a Rust str is UTF-8 text addressed by byte offsets. The methods below are defined on str, so they work on &str, &String, and literals. Most of them return slices that borrow from the original text and allocate nothing.
Searching
contains, starts_with, and ends_with return a bool. find and rfind return Option<usize>, the byte offset of the first or last match. Because the offset is a byte index, it is always a valid char boundary and is safe to use for slicing.
fn main() {
let s = "héllo wörld";
println!("{}", s.contains("wör"));
println!("{}", s.starts_with('h'));
println!("{:?}", s.find('l'));
println!("{:?}", s.rfind('l'));
println!("{:?}", s.find('z'));
if let Some(i) = s.find(' ') {
println!("before: {}, after: {}", &s[..i], &s[i + 1..]);
}
}The first l is at byte 3, not 2, because é takes two bytes. Do not treat the result as a character count.
Patterns
These methods accept a pattern. A pattern can be a char, a &str, a slice or array of chars, or a closure taking a char and returning bool.
fn main() {
let s = "a1b22c333";
println!("{:?}", s.find(char::is_numeric));
println!("{:?}", s.find(|c: char| c == 'b' || c == 'c'));
println!("{:?}", s.find(['b', 'c']));
}Splitting
split returns a lazy iterator of slices. Collect it only if you need a Vec.
fn main() {
let csv = "a,b,,c";
let parts: Vec<&str> = csv.split(',').collect();
println!("{:?}", parts);
println!("{:?}", " one two\tthree\n".split_whitespace().collect::<Vec<_>>());
println!("{:?}", "k=v=w".split_once('='));
println!("{:?}", "k=v=w".rsplit_once('='));
println!("{:?}", "a,b,c,d".splitn(2, ',').collect::<Vec<_>>());
println!("{:?}", "l1\nl2\r\nl3".lines().collect::<Vec<_>>());
}| Method | Behavior |
|---|---|
| `split(p)` | Splits at every match. Keeps empty pieces. |
| `split_whitespace()` | Splits on any whitespace run and skips empty pieces. |
| `splitn(n, p)` | Returns at most `n` pieces. The last piece holds the remainder. |
| `split_once(p)` | Splits at the first match into an `Option<(&str, &str)>`. |
| `lines()` | Splits on `\n` and `\r\n`. Drops the final empty line. |
Trimming
trim removes leading and trailing whitespace. trim_start and trim_end remove one side. trim_matches, strip_prefix, and strip_suffix take a pattern. Unlike trim_start_matches, strip_prefix removes the prefix once and returns an Option, so you can tell whether it was present.
fn main() {
println!("[{}]", " padded \n".trim());
println!("[{}]", "xxhixx".trim_matches('x'));
println!("{:?}", "v1.2".strip_prefix('v'));
println!("{:?}", "1.2".strip_prefix('v'));
println!("[{}]", "aaab".trim_start_matches('a'));
}Putting it together
This function parses key = value lines, ignoring blanks and comments. All returned slices borrow from the input.
fn parse_line(line: &str) -> Option<(&str, &str)> {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
return None;
}
let (key, value) = line.split_once('=')?;
Some((key.trim(), value.trim()))
}
fn main() {
let text = "# config\nname = Ferris\n\nlang=Rust\nbroken line";
for line in text.lines() {
match parse_line(line) {
Some((k, v)) => println!("{k} -> {v}"),
None => println!("skipped: {line:?}"),
}
}
}Common errors
- Using a
findresult as a char index. It is a byte offset. - Expecting
splitto drop empty pieces. - Using
trim_start_matcheswhen you meant to remove a prefix once. Usestrip_prefix. - Returning a slice of a local
String. The slice cannot outlive its owner, so return aStringinstead.
Exercise
What does "a-b-c".splitn(2, '-').collect::<Vec<>>() produce, and why does "x".stripprefix('y') return None instead of "x"?
Show answer
The first gives ["a", "b-c"], because splitn stops after two pieces and leaves the rest in the last one. strip_prefix returns Option<&str> so the caller can tell whether the prefix was present. Since "x" does not start with 'y', the result is None.
Exercise
Write an expression that takes " Name : Ferris " and yields the pair ("Name", "Ferris") with no surrounding whitespace.
Show answer
let (k, v) = " Name : Ferris ".split_once(':').unwrap(); (k.trim(), v.trim())