Skip to main content

How to Split a String in Rust with split

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

A string's split method cuts it into pieces at a separator, such as '-' or ",". It gives you the pieces one at a time; collect them into a Vec to keep them all.

Syntax​

Syntax
let pieces: Vec<&str> = text.split(separator).collect();
let pieces: Vec<&str> = text.splitn(n, separator).collect();
PartWhat it does
textThe string to split, a &str or a String.
separatorWhere to cut: a character such as '-', a string such as "::", or a slice of characters.
split(separator)Returns an iterator over the pieces between the separators.
splitn(n, separator)The same, but it stops at n pieces: the last piece holds the rest of the text.
.collect()Gathers the pieces into a collection.
Vec<&str>The collection to build: a list of string slices that point into text.

The documentation for str::split: "Returns an iterator over substrings of this string slice, separated by characters matched by a pattern." And: "If a string contains multiple contiguous separators, you will end up with empty strings in the output". The one for str::splitn says it is "restricted to returning at most n items. If n substrings are returned, the last substring (the nth substring) will contain the remainder of the string."

The Example​

The example splits the date 2026-11-28 at each -, splits it into only two pieces with splitn, and splits a,b,,c, which has two commas in a row, at each ,. Last, it takes only the first piece of the date.

Prerequisites​

  • Rust, installed with rustup, which comes with Cargo. This guide uses Rust 1.100.1.

Step 1: Create a Project​

Terminal
cargo new demo
cd demo
Output
Creating binary (application) `demo` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

cargo new demo creates a folder named demo with a Cargo.toml file, which describes the project, and src/main.rs, which holds the code. cd demo moves into it.

Step 2: Write the Code​

Replace the contents of src/main.rs with:

src/main.rs, which splits 2026-11-28 at each dash and with splitn into two pieces, splits a,b,,c at each comma, collects each result into a Vec and prints it, then prints the first piece of the date with next.

src/main.rs
fn main() {
let date = "2026-11-28";

let parts: Vec<&str> = date.split('-').collect();
println!("{parts:?}");

let two: Vec<&str> = date.splitn(2, '-').collect();
println!("{two:?}");

let list: Vec<&str> = "a,b,,c".split(',').collect();
println!("{list:?}");

let mut pieces = date.split('-');
println!("{:?}", pieces.next());
}
  • date.split('-') cuts the date at each -, and .collect() gathers the pieces into parts. The type, Vec<&str>, tells collect what to build.
  • {parts:?} prints the Vec in its debug format, with each piece in quotes.
  • date.splitn(2, '-') stops after two pieces.
  • pieces keeps the iterator itself, without collecting it. next() returns its next piece, the first one here. The iterator is mut because next() moves it forward.

Step 3: Run It​

Terminal
cargo run -q
Output
["2026", "11", "28"]
["2026", "11-28"]
["a", "b", "", "c"]
Some("2026")

A zsh terminal where cargo run -q prints the pieces 2026, 11 and 28, then 2026 and 11-28, then a, b, an empty string and c, then Some of 2026.

cargo run compiles the program and runs it, and -q hides Cargo's own status lines.

What Happened​

  • split('-') gave the three pieces of the date.
  • splitn(2, '-') stopped at two pieces, so the second one kept the rest of the text: "11-28".
  • The two commas in a row in a,b,,c had nothing between them, so that piece is an empty string, "".
  • next() returned Some("2026"). It wraps the piece in Some because an iterator can run out: once there are no pieces left, next() returns None.

Common Mistakes​

MistakeWhat happensDo this instead
Taking a piece by index straight from split, as in text.split('-')[0]error[E0608]: cannot index into a value of type `std::str::Split<'_, char>` Collect into a Vec first, or call .next()
Printing the iterator, println!("{p:?}")It prints Split(SplitInternal { start: 0, end: 3, ... instead of the piecesCollect it, then print the Vec
Collecting the pieces into Vec<String>error[E0277]: a value of type `Vec<String>` cannot be built from an iterator over elements of type `&str` Collect into Vec<&str>, or add .map(String::from) before .collect()
Splitting text with several spaces in a row on ' 'Empty pieces: "a b" gave ["a", "", "b"]Use split_whitespace(), which gave ["a", "b"]

Troubleshooting​

SymptomLikely causeFix
cannot index into a value of type `std::str::Split<'_, char>` split returns an iterator, not a list.collect() into a Vec<&str>
Empty strings in the resultTwo separators in a row, or one at the start or endExpected; drop them with .filter(|s| !s.is_empty())

FAQ​

Why are the pieces &str and not String?​

Each piece is a slice of the original text, so splitting copies nothing. To own the pieces, .map(String::from) before .collect() turned "a b" into a Vec<String>, ["a", "b"].

Can I split on a word or on several characters?​

Yes. "a::b".split("::") gave ["a", "b"], and a slice of characters splits at any of them: "2026-11-28 10:45".split(&['-', ' ', ':'][..]) gave ["2026", "11", "28", "10", "45"].

What does split("") do?​

It cuts between every character, and at the start and end: "abc".split("") gave ["", "a", "b", "c", ""].

Conclusion​

text.split(separator) cuts a string at each separator and returns the pieces as an iterator. Collect them into a Vec<&str> to keep them, use splitn to stop at a number of pieces, and next() to take just the first.

Additional Resources​