Sub topic 3
Searching, Splitting, and Converting Rust Strings
This chapter assumes basic Rust syntax, ownership and borrowing, and familiarity with Option and Result.
Searching, Splitting, and Trimming
String methods search without changing the original text. contains checks for a match, find returns its byte position, and starts_with checks a prefix. Methods such as trim, trim_start, and trim_end return borrowed slices.
fn main() {
let line = " name=Ferris ";
if line.contains('=') {
println!("separator at byte {}", line.find('=').unwrap());
}
if let Some((key, value)) = line.trim().split_once('=') {
println!("{key} -> {}", value.trim());
}
}split_once returns an Option<(&str, &str)>. The slices borrow from the original string, so they do not allocate.
Parsing Strings into Other Types
parse converts text into a type that implements FromStr. The target type often must be stated because many types can parse the same text.
fn main() {
let input = "42";
let number: Result<u32, _> = input.parse();
match number {
Ok(value) => println!("number: {value}"),
Err(error) => println!("invalid number: {error}"),
}
}Handle the Result instead of assuming that input is valid.
Handling Invalid UTF-8
String must contain valid UTF-8. When bytes come from a file, socket, or foreign interface, validate them with String::from_utf8. It returns FromUtf8Error when validation fails.
fn main() {
let bytes = vec![0xff, 0xfe];
match String::from_utf8(bytes) {
Ok(text) => println!("{text}"),
Err(error) => println!("invalid UTF-8: {error}"),
}
}Capacity and Avoiding Extra Allocations
A String grows its internal byte buffer as needed. If you know an approximate size, String::with_capacity can reduce reallocations.
fn main() {
let mut result = String::with_capacity(32);
result.push_str("hello");
result.push(' ');
result.push_str("Rust");
println!("{result}");
}Prefer borrowed slices for read-only work. Use format! or a new String when you need owned output.
`Cow<str>`: Borrow When You Can
Cow<'a, str> can hold either a borrowed &str or an owned String. This is useful when most inputs need no change.
use std::borrow::Cow;
fn normalize(input: &str) -> Cow<'_, str> {
if input.contains(' ') {
Cow::Owned(input.replace(' ', "_"))
} else {
Cow::Borrowed(input)
}
}
fn main() {
println!("{}", normalize("ready"));
println!("{}", normalize("needs editing"));
}`OsString`, `Path`, and `CString`
Use OsString for operating-system text, because file names are not guaranteed to be UTF-8. Use Path for file paths. Use CString for C APIs that require a null-terminated string.
use std::ffi::{CString, OsString};
use std::path::Path;
fn main() {
let name = OsString::from("report.txt");
let path = Path::new(&name);
if let Some(text) = path.to_str() {
println!("{text}");
}
let c_name = CString::new("report.txt").expect("embedded NUL");
println!("{c_name:?}");
}Path::to_str returns Option<&str> because conversion to UTF-8 can fail. CString::new returns an error when the input contains an interior null byte.
Exercise
Which method safely separates "port=8080" into two borrowed pieces?
Show answer
split_once('='), which returns Some(("port", "8080")).