How to get the last character a & str?

In Python, it will be final_char = mystring[-1]. How can I do the same in Rust?

I tried

mystring[mystring.len() - 1]

but i get an error the type 'str' cannot be indexed by 'usize'

+4
source share
1 answer

Here's how you get the latter char(which might not be what you think of as a “character”):

mystring.chars().last().unwrap();

Use unwraponly if you are sure that your line has at least one char.


Warning . About the general case (do the same as mystring[-n]in python): UTF-8 strings should not be used through indexing, since indexing is not O (1) (a string in Rust is not an array). Please read this for more information.

, , Python, Rust:

mystring.chars().rev().nth(n - 1) // python: mystring[-n]

, char.

Python, :

trait StrExt {
    fn from_end(&self, n: usize) -> char;
}

impl<'a> StrExt for &'a str {
    fn from_end(&self, n: usize) -> char {
        self.chars().rev().nth(n).expect("Index out of range in 'from_end'")
    }
}

fn main() {
    println!("{}", "foobar".from_end(2)) // prints 'b'
}
+6

Source: https://habr.com/ru/post/1693246/


All Articles