Working with text
Text is where Rust’s honesty about memory shows up first. A String is bytes that are guaranteed
to be valid UTF-8, so s[0] cannot work, and s.len() is not a character count.
These are the articles you need when the string will not slice, will not reverse, or has a newline in it you did not see.
Articles
Section titled “Articles”- What is the difference between String and &str?owned versus borrowed text
- When to use String::from, to_string, or into?three spellings, three intents
- How to build a string from parts+, push_str, and format!
- How to append to a String without extra allocationspush_str into a buffer you keep
- How to format strings with println! and format!named arguments and inline capture
- How to print without a trailing newlineprint! plus flush, and why flush matters
- How to print to standard erroreprintln!, and keeping stdout clean for pipes
- How to split a stringsplit, split_whitespace, split_once
- How to iterate over the characters of a stringchars, bytes, and which one you need
- How to slice a string safelychar boundaries, and the panic at the wrong byte
- Why can’t you index into a String?UTF-8 makes s[0] meaningless
- How to reverse a stringreverse() does not exist for a reason
- How to handle UTF-8 textvalid by construction, and what that buys
- How to convert a Vec of bytes to a Stringfrom_utf8 versus from_utf8_lossy
- How to match and replace text with regexcompile once, and avoid recompiling in a loop
- How to replace placeholders in a templatereplace, and when a real templating crate pays
- How to trim whitespace and strip characterstrim, trim_matches, and the line ending you did not see
- How to check whether a string contains a substringcontains, starts_with, and the case-insensitive search
- How to pad and align text in a tablewidth, fill, and the crate that does it for you