Skip to content

str::rfind

str methods · Strings

Level: reference · for working programmers

One line: The byte offset of the last match — the same Option<usize> as find, searching from the end.

pub fn rfind<P: Pattern>(&self, pat: P) -> Option<usize>
where
    for<'a> P::Searcher<'a>: ReverseSearcher<'a>,

Stable since 1.0.0.

The offset still counts from the start of the string; only the search direction is reversed. So "a.b.c".rfind('.') is 3, not 1.

This is the method for splitting off a trailing part when the delimiter may appear more than once — an extension, the last path segment, the final colon in host:port:extra. rsplit_once is usually the better spelling of the same idea.

Reverse searching needs the pattern's searcher to be a ReverseSearcher; all four usual shapes are.

Example

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

fn main() {
    let path = "/usr/local/share/doc";

    println!("{:?} {:?}", path.find('/'), path.rfind('/'));

    // The last segment, two ways.
    if let Some(i) = path.rfind('/') {
        println!("{:?}", &path[i + 1..]);
    }
    println!("{:?}", path.rsplit_once('/'));

    // Extensions: rfind takes the last dot, find would take the first.
    let file = "archive.tar.gz";
    println!("{:?} {:?}",
             file.find('.').map(|i| &file[i + 1..]),
             file.rfind('.').map(|i| &file[i + 1..]));

    // Offsets always count from the front.
    println!("{:?}", "a.b.c".rfind('.'));
    println!("{:?}", "abc".rfind('z'));
}

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

Some(0) Some(16)
"doc"
Some(("/usr/local/share", "doc"))
Some("tar.gz") Some("gz")
Some(3)
None

See also

str::rfind in the standard library ↗

Po polsku

Przedrostek r odwraca wyłącznie kierunek szukania, a nie sposób numerowania: zwrócone przesunięcie nadal liczy się od początku łańcucha, dlatego "a.b.c".rfind('.') to 3, a nie 1. To metoda do odcinania końcówki tam, gdzie separator może pojawić się wiele razy — widać to na "archive.tar.gz", gdzie find daje "tar.gz", a rfind "gz". Uwaga na idiom &path[i + 1..] z przykładu: działa, bo / zajmuje jeden bajt, ale przy separatorze pokroju ł albo zamiast 1 trzeba dodać c.len_utf8(), inaczej trafisz w środek znaku i program panikuje. Zwykle i tak czytelniej wychodzi rsplit_once, które zwraca od razu obie części bez ręcznej arytmetyki na przesunięciach — w wydruku Some(("/usr/local/share", "doc")).

Szukaj po polsku: szukanie od końca łańcucha znaków · ostatni separator i rozszerzenie pliku · rust rfind vs find · rust rsplit_once