str::splitn¶
Level: reference · for working programmers
One line: At most n pieces — after n−1 splits the remainder comes back whole, separators and all.
Stable since 1.0.0.
This is the method for "split off the first field and leave the rest alone". A config line like key = a = b has to become key and a = b, not three pieces, and splitn(2, '=') says exactly that.
The remainder keeps its separators, which is the entire point and the thing to check when a value comes back looking mangled.
n == 0 yields nothing at all — not one piece, none. n == 1 yields the whole string as a single piece without searching.
For the extremely common n == 2 case, split_once is better: it returns Option<(&str, &str)>, so a missing delimiter is a None you must handle rather than a one-element iterator you might not notice.
Example¶
str_splitn.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let line = "key = a = b";
println!("{:?}", line.split('=').collect::<Vec<&str>>());
println!("{:?}", line.splitn(2, '=').collect::<Vec<&str>>());
println!("{:?}", line.splitn(3, '=').collect::<Vec<&str>>());
// Edge values of n.
println!("{:?}", line.splitn(0, '=').collect::<Vec<&str>>());
println!("{:?}", line.splitn(1, '=').collect::<Vec<&str>>());
// n=2 is nearly always better written as split_once.
println!("{:?}", line.split_once('='));
println!("{:?}", "no delimiter".split_once('='));
println!("{:?}", "no delimiter".splitn(2, '=').collect::<Vec<&str>>());
}
Verified output of str_splitn.rs — regenerated by tools/run_examples.py, never hand-typed.
["key ", " a ", " b"]
["key ", " a = b"]
["key ", " a ", " b"]
[]
["key = a = b"]
Some(("key ", " a = b"))
None
["no delimiter"]
See also¶
str::split_once— the n=2 case, with a type that reports a missstr::rsplitn— the same limit applied from the rightstr::split— no limitstr::split_inclusive— keep the separator on the piece before it
str::splitn in the standard library ↗
Po polsku¶
Liczba w splitn to liczba kawałków, a nie liczba cięć — i to pierwsza rzecz do sprawdzenia przy przepisywaniu kodu z Pythona, gdzie maxsplit liczy właśnie cięcia: "key = a = b".split("=", 2) daje tam trzy części, a line.splitn(2, '=') w Ruscie dwie. Przelicznik jest prosty — rustowe n odpowiada pythonowemu maxsplit + 1 — i porządkuje też przypadki skrajne: splitn(1, ..) oddaje cały tekst, w ogóle niczego nie szukając, a splitn(0, ..) nie oddaje nic, czyli pustą sekwencję, a nie jeden pusty kawałek. Sens metody to „odetnij pierwsze pole, resztę zostaw w spokoju”: reszta wraca w całości, razem ze swoimi separatorami (["key ", " a = b"]), i właśnie to sprawdź, gdy wartość wygląda na poszatkowaną. Przy najczęstszym n == 2 sięgnij jednak po split_once, bo brak separatora zgłasza jako None, a nie jako jednoelementowy iterator, który łatwo przeoczyć.
Szukaj po polsku: ograniczenie liczby części przy podziale · odpowiednik maxsplit w Ruscie · rust splitn vs split_once · rust splitn remainder keeps separators