Text has more than one length.
Own, borrow, build, and iterate through UTF-8 text.
01 Understand the contract
String owns a growable UTF-8 buffer; str is the dynamically sized text type usually used through &str. Use push for a char, push_str for a string slice, and format! when building a new formatted String. len counts bytes, chars iterates Unicode scalar values, and split_whitespace separates runs of whitespace. Case conversion can change the byte length. Be explicit about the text operation your product needs, especially for names, search, and cursor movement.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
fn main() {
let mut title = String::from("Rust");
title.push_str(" café");
println!("{title}");
println!("bytes={}, scalars={}", title.len(), title.chars().count());
println!(
"{}",
title.split_whitespace().collect::<Vec<_>>().join(" / ")
);
}Rust café bytes=10, scalars=9 Rust / café
- 1
The é needs two bytes in UTF-8.
- 2
split_whitespace returns borrowed words.
- 3
join constructs a new owned String.
cargo run -p lesson_strings03 Mind the boundary
04 Your next build
Reverse the Unicode scalar sequence of a string and test an accented word.
Reveal one possible solution +
fn reverse(s: &str) -> String {
s.chars().rev().collect()
}
fn main() {
assert_eq!(reverse("café"), "éfac");
assert_eq!(reverse(""), "");
}05 Check your reasoning
Which method counts UTF-8 bytes?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.