Sub topic 10
Splitting a Line into Whitespace-Separated Values
Earlier chapters read a whole line into a String, trimmed it, and parsed it as one value. Many programs receive several values on one line, such as 3 4 5 or add 10 20. This chapter covers how to split such a line into tokens and turn those tokens into typed values.
It assumes you can use read_line, handle its io::Result, and call parse on a trimmed string. It also assumes you know basic Vec, iterator, and match syntax.
Why not split on a single space
The obvious tool is split(' '). It splits on exactly one space character, so any irregular spacing produces extra pieces. Users type double spaces and tabs, and the line also ends with a newline.
fn main() {
let line = " 10 20\t30 \n";
let a: Vec<&str> = line.split(' ').collect();
let b: Vec<&str> = line.split_whitespace().collect();
println!("{a:?}");
println!("{b:?}");
}This prints:
["", "", "10", "", "", "20\t30", "\n"]
["10", "20", "30"]split(' ') returns empty strings for each extra space. It leaves the tab inside "20\t30" and returns the newline as its own piece. split_whitespace avoids all of this. It treats any run of whitespace as one separator, ignores leading and trailing whitespace, and never yields an empty token. Because the trailing newline counts as whitespace, you don't need to call trim first.
What split_whitespace returns
str::split_whitespace returns an iterator of &str slices. Each slice borrows from the original string, so no new strings are allocated. The iterator is lazy and does its work as you consume it. You can do any of the following with it:
- Loop over it with
for. - Call
next()to take tokens one at a time. - Use
collect()to gather the tokens into aVec<&str>. - Chain
map,filter, orsumonto it.
Since the tokens borrow from the line, the String that holds the line must stay alive while you use them. Declaring the String before the loop or function body is usually enough.
The following table compares the splitting methods you are most likely to consider.
| Method | Splits on | Empty tokens | Typical use |
|---|---|---|---|
| `split(' ')` | One space character | Yes, for repeated spaces | Fixed formats where empty fields matter |
| `split(',')` | One comma | Yes | CSV-like data (simple cases only) |
| `split_whitespace()` | Any run of Unicode whitespace | Never | Free-form numbers and words |
| `split_ascii_whitespace()` | Any run of ASCII whitespace | Never | Same, but ASCII only and slightly faster |
| `split_once(' ')` | The first space only | Not applicable | Command word plus the rest |
split_whitespace uses the Unicode definition of whitespace, which includes the no-break space (U+00A0) and the ideographic space (U+3000). split_ascii_whitespace only recognizes the ASCII characters. For terminal input from a user, the difference rarely matters. For machine-generated input where you want strict behavior, the ASCII version is the safer choice.
Parsing every token on a line
The most common pattern is to read one line and parse every token as the same type. You can do this by mapping parse over the iterator and collecting the results.
use std::io;
fn main() -> io::Result<()> {
let mut line = String::new();
io::stdin().read_line(&mut line)?;
let parsed: Result<Vec<i32>, _> = line
.split_whitespace()
.map(|token| token.parse::<i32>())
.collect();
match parsed {
Ok(numbers) => println!("sum = {}", numbers.iter().sum::<i32>()),
Err(e) => println!("bad number: {e}"),
}
Ok(())
}The map closure produces a Result<i32, ParseIntError> for each token. Rust can collect an iterator of Result<T, E> into a single Result<Vec<T>, E>. The result is Ok(vec) if every token parsed, and otherwise it is the first Err. Collection stops at that first error, so later tokens are never parsed.
With the input 3 4 5 the program prints sum = 12. With 3 4 five it prints bad number: invalid digit found in string.
This approach has a drawback. The error does not say which token was wrong. If you need that, parse in a loop and keep the token for the message:
fn parse_all(line: &str) -> Result<Vec<i32>, String> {
let mut numbers = Vec::new();
for token in line.split_whitespace() {
let n = token
.parse::<i32>()
.map_err(|e| format!("{token:?} is not a valid integer: {e}"))?;
numbers.push(n);
}
Ok(numbers)
}
fn main() {
println!("{:?}", parse_all("1 2 3"));
println!("{:?}", parse_all("1 x 3"));
}This prints Ok([1, 2, 3]) and then Err("\"x\" is not a valid integer: invalid digit found in string"). The map_err call converts the ParseIntError into a String that includes the offending token.
Lines with a fixed shape
Sometimes a line holds a fixed number of values, possibly of different types. Pulling tokens off the iterator with next() lets you check the count and parse each token as you go. The ? operator works on Option too, so a function that returns Option can stop at the first missing or invalid token.
use std::io;
fn parse_point(line: &str) -> Option<(f64, f64)> {
let mut parts = line.split_whitespace();
let x = parts.next()?.parse::<f64>().ok()?;
let y = parts.next()?.parse::<f64>().ok()?;
if parts.next().is_some() {
return None; // extra token
}
Some((x, y))
}
fn main() -> io::Result<()> {
let mut line = String::new();
io::stdin().read_line(&mut line)?;
match parse_point(&line) {
Some((x, y)) => println!("distance from origin: {}", x.hypot(y)),
None => println!("expected exactly two numbers, like: 3 4"),
}
Ok(())
}Each step does one of three things. parts.next()? returns None if the token is missing. .parse::<f64>().ok()? converts a parse failure into None and returns early. The final parts.next().is_some() check rejects lines with too many values. The input 3 4 prints distance from origin: 5.
Converting errors to None discards the reason for failure. That is fine when one message covers every case, as above. If you want different messages for "too few values" and "not a number", return a Result with your own error type or a String.
A command word followed by arguments
Interactive programs often read lines such as add 3 4. In that case the first token chooses the action and the rest are arguments. Collecting the tokens into a Vec<&str> and matching on a slice pattern handles this without index arithmetic.
use std::io::{self, BufRead};
fn num(s: &str) -> Result<i64, String> {
s.parse().map_err(|e| format!("{s:?}: {e}"))
}
fn eval(line: &str) -> Result<i64, String> {
let tokens: Vec<&str> = line.split_whitespace().collect();
match tokens.as_slice() {
["add", a, b] => Ok(num(a)? + num(b)?),
["mul", a, b] => Ok(num(a)? * num(b)?),
[] => Err("empty line".to_string()),
[cmd, ..] => Err(format!("unknown or malformed command: {cmd}")),
}
}
fn main() -> io::Result<()> {
for line in io::stdin().lock().lines() {
let line = line?;
match eval(&line) {
Ok(value) => println!("{value}"),
Err(msg) => eprintln!("error: {msg}"),
}
}
Ok(())
}The patterns are checked in order. ["add", a, b] matches only when the line has exactly three tokens and the first is add. The empty pattern [] matches a blank line. The last pattern [cmd, ..] catches everything else, including add 1 (too few arguments) and sub 1 2 (unknown command). In the arm bodies a and b have type &&str, and num accepts them because Rust automatically dereferences them to &str.
How the pieces fit together
The next diagram shows the path from raw text to typed values.
Edge cases and gotchas
- Blank lines produce zero tokens. An empty or whitespace-only line yields an empty iterator.
collect()gives an emptyVec, andnext()returnsNoneimmediately. Code that doestokens[0]panics on such a line, so usenext(),first(), or a slice pattern instead. - A single
parseerror can hide the real problem. Passing the whole line toparsefails for"3 4", because the space is not part of a number. Split first, then parse each token. - Tokens borrow from the line. If you want to keep tokens after the line buffer is reused or cleared, convert them with
to_string()orString::from. Parsed numbers are plain values and do not borrow anything. - Reusing a buffer with
read_lineappends. In a loop, callline.clear()before eachread_line, or create a freshString. Otherwise the tokens from earlier lines remain in the buffer. - Quoted text is not handled.
split_whitespaceknows nothing about quotes, sosay "hello world"yields the tokenssay,"hello, andworld". Usesplit_onceto take the rest of a line as a single string, or use a parsing crate. - Numbers separated by commas need another separator. For
1,2,3, usesplit(',')and trim each piece.split_whitespacereturns the whole1,2,3as one token.
Summary of the technique
- Read a line into a
String. - Call
split_whitespace()on it. You do not needtrimfor the tokens. - Decide how the tokens map to values. For uniform values, use
map(parse).collect::<Result<Vec<_>, _>>(). For a fixed shape, usenext()with?. For commands, collect into aVec<&str>and match a slice pattern. - Report errors using the token that failed.
The next chapters build on this. Reading a whole input at once with read_to_string gives you one large string that you can split the same way.
Exercise
A user types 7 8 9 (two leading spaces, two spaces between 7 and 8, one trailing space) followed by Enter. How many items does line.split(' ').count() return, compared with line.split_whitespace().count()? Then write a function fn sum_line(line: &str) -> Result<i32, std::num::ParseIntError> that returns the sum of all integers on a line, and say what it returns for a blank line.
Show answer
The line is " 7 8 9 \n". split(' ') yields "", "", "7", "", "8", "9", "\n", which is 7 items. split_whitespace() yields "7", "8", "9", which is 3 items. One solution:
fn sumline(line: &str) -> Result<i32, std::num::ParseIntError> {
let numbers: Result<Vec<i32>, > = line
.splitwhitespace()
.map(|t| t.parse::<i32>())
.collect();
Ok(numbers?.iter().sum())
}
A shorter version is `line.splitwhitespace().map(|t| t.parse::<i32>()).sum(), because Result<i32, E> implements Sum. For a blank line there are no tokens, so the sum of an empty sequence is Ok(0)`. Whether that is acceptable depends on your program. If a blank line should be an error, check for an empty token list first.
Exercise
Using a slice pattern like the one in eval, add a command neg N that returns the negation of one integer. Which new arm do you add, and where must it go relative to the [cmd, ..] arm?
Show answer
Add ["neg", a] => Ok(-num(a)?), before the [cmd, ..] arm. Arms are checked in order, and [cmd, ..] matches any non-empty line. If neg came after it, the new arm would never run, and the compiler would report it as unreachable.