Advanced strings in Rust
| 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