Skip to content

str::rsplitn

str methods · Strings

Level: reference · for working programmers

One line: At most n pieces, splitting from the right — the remainder that comes back whole is the beginning of the string.

pub fn rsplitn<P: Pattern>(&self, n: usize, pat: P) -> RSplitN<'_, P>
where
    for<'a> P::Searcher<'a>: ReverseSearcher<'a>,

Stable since 1.0.0.

This is where direction genuinely changes the answer, unlike plain rsplit. "a.b.c".splitn(2, '.') gives ["a", "b.c"]; rsplitn(2, '.') gives ["c", "a.b"].

Note the order: the pieces come back right-to-left, so the first item is the last field and the whole remainder is last. That catches people who expect ["a.b", "c"].

The classic use is splitting a name from its extension, or a path from its final segment, when the delimiter appears an unknown number of times. rsplit_once is the clearer spelling for n == 2.

Example

str_rsplitn.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    let file = "a.b.c";

    println!("{:?}", file.splitn(2, '.').collect::<Vec<&str>>());
    println!("{:?}", file.rsplitn(2, '.').collect::<Vec<&str>>());

    // Right-to-left order: last field first, remainder last.
    println!("{:?}", file.rsplitn(3, '.').collect::<Vec<&str>>());

    // Stem and extension, the readable way.
    println!("{:?}", file.rsplit_once('.'));

    // A path's parent and final segment.
    let path = "/usr/local/bin/rustc";
    let mut it = path.rsplitn(2, '/');
    let name = it.next();
    let parent = it.next();
    println!("{name:?} in {parent:?}");
}

Verified output of str_rsplitn.rs — regenerated by tools/run_examples.py, never hand-typed.

["a", "b.c"]
["c", "a.b"]
["c", "b", "a"]
Some(("a.b", "c"))
Some("rustc") in Some("/usr/local/bin")

See also

str::rsplitn in the standard library ↗

Po polsku

W rsplitn dzieją się naraz dwie rzeczy i warto je rozdzielić, bo pomylenie ich jest źródłem całego zamieszania: n ogranicza liczbę kawałków (nie cięć), a ponieważ cięcia liczone są od prawej, nierozcięta reszta to początek łańcucha znaków; osobno od tego iterator wydaje kawałki od prawej do lewej. Dlatego "a.b.c".rsplitn(2, '.') to ["c", "a.b"], a nie oczekiwane przez wielu ["a.b", "c"] — najpierw ostatnie pole, reszta na koniec. To odróżnia rsplitn od zwykłego rsplit, gdzie kierunek zmienia tylko kolejność, a nie to, co dostajesz. Jeśli zależy Ci na parze w kolejności czytania, dla n == 2 czytelniejszy jest rsplit_once, który do tego odróżnia brak separatora (None) od pustego pola.

Szukaj po polsku: ograniczenie liczby części przy dzieleniu · nierozcięta reszta łańcucha · rust rsplitn · rust splitn vs rsplitn · rust rsplitn reversed order