Skip to content

str::rsplit_terminator

str methods · Strings

Level: reference · for working programmers

One line: split_terminator from the right — still drops the trailing empty piece, and yields what is left back to front.

pub fn rsplit_terminator<P: Pattern>(&self, pat: P) -> RSplitTerminator<'_, P>
where
    for<'a> P::Searcher<'a>: ReverseSearcher<'a>,

Stable since 1.0.0.

The pieces are the same as split_terminator; only the iteration order is reversed. The rule about which empty is dropped does not flip with the direction — it is still the piece after the final separator that disappears, because that is a property of the string, not of how you walk it.

That is the thing to check: ",a".rsplit_terminator(',') is ["a", ""] — the leading empty survives and arrives last.

Example

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

fn main() {
    for input in ["a,b,", ",a,b", "a,,b"] {
        println!("{:<7}  fwd {:<20}  rev {:?}",
                 format!("{input:?}"),
                 format!("{:?}", input.split_terminator(',').collect::<Vec<&str>>()),
                 input.rsplit_terminator(',').collect::<Vec<&str>>());
    }

    // The dropped piece is the trailing one either way: here the LEADING
    // empty survives, and arrives last because the order is reversed.
    println!("{:?}", ",a".rsplit_terminator(',').collect::<Vec<&str>>());

    // The last real line of a newline-terminated file, cheaply.
    let file = "alpha\nbeta\ngamma\n";
    println!("{:?}", file.rsplit_terminator('\n').next());
}

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

"a,b,"   fwd ["a", "b"]            rev ["b", "a"]
",a,b"   fwd ["", "a", "b"]        rev ["b", "a", ""]
"a,,b"   fwd ["a", "", "b"]        rev ["b", "", "a"]
["a", ""]
Some("gamma")

See also

str::rsplit_terminator in the standard library ↗

Po polsku

Nazwa mówi wszystko, jeśli przeczytać ją dosłownie: w rsplit_terminator separator jest zakończeniem elementu, a nie rozdzielaczem między elementami — dlatego "alpha\nbeta\ngamma\n" ma trzy pola, a nie cztery. Pułapka jest w przedrostku r: odwraca on kolejność przechodzenia, ale nie to, który pusty kawałek znika. Zawsze wypada ten po ostatnim separatorze, bo to cecha samego łańcucha znaków, a nie kierunku, z którego go czytamy — stąd ",a".rsplit_terminator(',') daje ["a", ""]: wiodąca pustka przeżywa i po prostu przychodzi na końcu. Jeśli intuicja podpowiada, że „skoro czytam od tyłu, to i pustka ucieka z drugiej strony”, to właśnie ta jedna linijka wyjścia jest kontrprzykładem wartym zapamiętania.

Szukaj po polsku: separator jako zakończenie elementu · puste pola przy dzieleniu łańcucha · iteracja od końca · rust rsplit_terminator · rust split_terminator trailing empty