Advanced strings in Rust

Contents
Chars not bytes
Split lines and whitespace
Parse numbers
Format widths

Chars not bytes

Rust text is UTF-8, so one visible character can span several bytes. The chars method walks user perceived characters instead of raw byte positions.

Prefer chars or grapheme aware crates for display work, and touch raw bytes only for encodings and protocols.

fn main() { let s = String::from("abc"); for c in s.chars() { println!("got one"); } }

The loop visits three characters for this plain text. The same loop stays correct for wider alphabets where byte counts diverge.

Split lines and whitespace

Split methods cut text on whitespace or newlines. Split_whitespace skips empty gaps, while lines keeps one item per row, so pick the cut that matches the input shape.

Both return iterators of string slices, which borrow the original text with no extra allocation.

fn main() { let s = String::from("a b\nc"); for w in s.split_whitespace() { println!("word"); } }

The sample holds three words across two rows. The loop prints one marker per word and ignores the exact spacing between them.

Parse numbers

The parse method converts a string slice into numbers and other core types. The target type comes from context, so annotate the binding or use a turbofish at the call.

Parse returns a Result, so pair it with unwrap_or, map_err, or the question mark instead of ignoring failure.

fn main() { let s = String::from("42"); let n: i32 = s.parse().unwrap_or(0); println!("done"); }

Clean digits become 42 while broken input falls back to 0. The annotation tells parse which number type to build.

Format widths

Format strings align values into fixed widths for tables and logs. A greater sign pads on the left and a less sign pads on the right, with the width after the sign.

The same mini language also sets precision and fill, so one macro covers most layout needs.

fn main() { println!("{:>6}", 42); println!("{:<6}", 42); }

The first line right aligns the number and the second line left aligns it. Both reserve six columns, which lines up values in plain text reports.

Next: Vec methods

Article author: Arthur Isaev

Related articles
Rust
Rust course: zero to hero in 50 lessons
What is Rust and where it runs
Install Rust
cargo new
Your first program
Variables
Numbers
Strings
Booleans
Tuples
Arrays
Vectors
Slices
if and else
match
Loops
Ownership
Borrowing
Lifetimes
Functions
Structs
Enums in Rust
Advanced match in Rust
Option combinators in Rust
Result and the question mark in Rust
Advanced strings in Rust
Vec methods in Rust
HashMaps in Rust
Modules in Rust
Crates and workspaces in Rust
Testing in Rust
Error handling
Traits
Generics
Trait bounds
Closures
Iterators
Smart pointers
Threads
Mutex and Arc
Files
CLI arguments
Environment variables
Diagnostics
Time
Parsing strings
TCP networking
Capstone: wordfreq CLI
Capstone: tiny HTTP server
Modern Rust tour
Hero roadmap: the whole course on one page
Install Rust on Windows 11
Install Rust on Ubuntu
Install Rust on Rocky Linux
Install Rust on macOS
Install Rust on FreeBSD
Rust in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: