Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the last occurrence of a char in a string?

Tags:

string

rust

I want to find the index of the last forward slash / in a string. For example, I have the string /test1/test2/test3 and I want to find the location of the slash before test3. How can I achieve this?

In Python, I would use rfind but I can't find anything like that in Rust.

like image 461
Kabard Avatar asked Apr 30 '18 13:04

Kabard


2 Answers

You need to use std::str::rfind. Note that it returns an Option<usize>, so you will need to account for that when checking its result:

fn main() {
    let s = "/test1/test2/test3";
    let pos = s.rfind('/');

    println!("{:?}", pos); // prints "Some(12)"
}
like image 69
ljedrz Avatar answered Nov 15 '22 10:11

ljedrz


@ljedrz's solution will not give you the correct result if your string contains non-ASCII characters.

Here is a slower solution but it will always give you correct answer:

let s = "/test1/test2/test3";
let pos = s.chars().count() - s.chars().rev().position(|c| c == '/').unwrap() - 1;

Or you can use this as a function:

fn rfind_utf8(s: &str, chr: char) -> Option<usize> {
    if let Some(rev_pos) = s.chars().rev().position(|c| c == chr) {
        Some(s.chars().count() - rev_pos - 1)
    } else {
        None
    }
}
like image 23
OverShifted Avatar answered Nov 15 '22 09:11

OverShifted