str::rsplit¶
Level: reference · for working programmers
One line: split from the right — the same pieces, yielded last-to-first.
pub fn rsplit<P: Pattern>(&self, pat: P) -> RSplit<'_, P>
where
for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
Stable since 1.0.0.
The pieces are identical to split; only the order is reversed. "a,b,c".rsplit(',') is ["c", "b", "a"].
That reversed order is the thing people trip on. If you want the pieces in reading order but the splitting done from the right, that is rsplitn or rsplit_once — the direction only matters when a limit is involved, and on an unlimited split the only difference is which end the iterator starts at.
Where it earns its keep is .next(): the last field of a line, without collecting the rest.
Example¶
str_rsplit.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let s = "a,b,c";
println!("{:?}", s.split(',').collect::<Vec<&str>>());
println!("{:?}", s.rsplit(',').collect::<Vec<&str>>());
// The everyday use: the last field, cheaply.
println!("{:?}", s.rsplit(',').next());
// Same pieces, so reversing gets reading order back.
let mut back: Vec<&str> = s.rsplit(',').collect();
back.reverse();
println!("{:?}", back);
println!("{}", back == s.split(',').collect::<Vec<&str>>());
// Empty pieces behave exactly as they do forwards.
println!("{:?}", "a,,c".rsplit(',').collect::<Vec<&str>>());
}
Verified output of str_rsplit.rs — regenerated by tools/run_examples.py, never hand-typed.
See also¶
str::split— the forward directionstr::rsplitn— where the direction actually changes the piecesstr::rsplit_once— the last delimiter, two piecesstr::rsplit_terminator— drops a leading empty piece instead
str::rsplit in the standard library ↗
Po polsku¶
rsplit tnie dokładnie to samo co split, tylko idzie od prawej: "a,b,c".rsplit(',') daje ["c", "b", "a"] — te same kawałki, odwrócona kolejność. Tu siedzi pułapka, bo „dzielenie od końca” brzmi jak inny podział, a przy braku limitu jedyną różnicą jest to, z którego końca rusza iterator (puste kawałki zachowują się identycznie: "a,,c" daje ["c", "", "a"], a zwykłe reverse() przywraca kolejność czytania). Po rsplit sięgaj wtedy, gdy interesuje cię samo next(), czyli ostatnie pole bez zbierania reszty; jeśli natomiast chcesz kawałki w naturalnej kolejności, ale cięte od końca, to zadanie dla rsplitn albo rsplit_once — dopiero z limitem kierunek naprawdę zmienia wynik.
Szukaj po polsku: dzielenie łańcucha od prawej · ostatnie pole tekstu · rust rsplit vs split · rust str rsplit last field