Sub topic 10
Splitting a Line into Whitespace-Separated Values
This chapter assumes you can already read a line with read_line, handle its io::Result, and call parse on trimmed text. You should also be comfortable with match and with &str versus String. Here you will turn one line such as 3 14 -7 into several typed values.
Why one line often holds many values
Programs often receive several values on one line, such as 10 20 for a width and a height. read_line gives you the whole line as one String. You must split it into pieces called tokens. A token is a run of non-whitespace characters. You then parse each token on its own.
Using split_whitespace
str::split_whitespace returns an iterator over the tokens. It skips any amount of spaces, tabs, and newlines between them. Leading and trailing whitespace produce no tokens, so you do not need to call trim first.
use std::io;
fn main() -> io::Result<()> {
let mut line = String::new();
io::stdin().read_line(&mut line)?;
let tokens: Vec<&str> = line.split_whitespace().collect();
println!("{} tokens: {:?}", tokens.len(), tokens);
Ok(())
}Each token is a &str that borrows from line. line must stay alive as long as you use the tokens.
Parsing every token
To parse all tokens, map each one through parse. Then collect the results into a Result<Vec<_>, _>. This all-or-nothing form stops at the first bad token and returns its error.
use std::io;
use std::num::ParseIntError;
fn parse_all(line: &str) -> Result<Vec<i32>, ParseIntError> {
line.split_whitespace().map(|t| t.parse::<i32>()).collect()
}
fn main() -> io::Result<()> {
let mut line = String::new();
io::stdin().read_line(&mut line)?;
match parse_all(&line) {
Ok(nums) => println!("sum = {}", nums.iter().sum::<i32>()),
Err(e) => println!("bad token: {e}"),
}
Ok(())
}Because collect stops at the first Err, you get one error and no partial list. If you would rather skip bad tokens, match on each parse call instead, as the next section does.
Many lines, many tokens
For piped input, lock stdin and iterate over lines(). Then split each line. This keeps the memory use of one line at a time.
use std::io::{self, BufRead};
fn main() -> io::Result<()> {
let mut sum: i64 = 0;
for line in io::stdin().lock().lines() {
let line = line?;
for token in line.split_whitespace() {
match token.parse::<i64>() {
Ok(n) => sum += n,
Err(_) => eprintln!("skipping {token:?}"),
}
}
}
println!("sum = {sum}");
Ok(())
}The warning goes to eprintln!, which writes to standard error. The sum on standard output stays clean when you redirect it.
Fixed positions
Sometimes each position has a meaning, such as width height. Keep the iterator and call next once per field.
fn parse_size(line: &str) -> Option<(u32, u32)> {
let mut parts = line.split_whitespace();
let w = parts.next()?.parse().ok()?;
let h = parts.next()?.parse().ok()?;
if parts.next().is_some() {
return None;
}
Some((w, h))
}
fn main() {
println!("{:?}", parse_size(" 640 480\n"));
println!("{:?}", parse_size("640"));
println!("{:?}", parse_size("1 2 3"));
}This prints Some((640, 480)), None, and None. The ? operator on an Option returns None early. The final next() check rejects extra tokens. The compiler infers u32 for both parse calls from the return type.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Parse error on the last token | Used `split(' ')`, so the newline is still attached | Use `split_whitespace` |
| `collect` type error | The target type is not stated | Write `Vec<&str>` or `Result<Vec<i32>, _>` |
| Borrow error after reusing the `String` | Tokens still borrow the line | Convert to owned values before clearing or reusing it |
| Missing values go unnoticed | Indexing or `unwrap` on a short line | Use `next()` with `?` or `match` |
Exercise
Write a function fn average(line: &str) -> Option<f64> that parses every whitespace-separated token in line as an f64 and returns their average. Return None if the line has no tokens or any token is not a number.
Show answer
fn average(line: &str) -> Option<f64> { let nums: Vec<f64> = line .splitwhitespace() .map(|t| t.parse::<f64>()) .collect::<Result<, >>() .ok()?; if nums.isempty() { return None; } Some(nums.iter().sum::<f64>() / nums.len() as f64) }