Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last character of a &str?

Tags:

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

I have tried

mystring[mystring.len() - 1]

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

like image 603
B B Avatar asked Feb 06 '18 11:02

B B


People also ask

How do I get the last character of a string?

To get the last character of a string, call the charAt() method on the string, passing it the last index as a parameter. For example, str. charAt(str. length - 1) returns a new string containing the last character of the string.

How do you find the last occurrence of a character?

strrchr() — Locate Last Occurrence of Character in String The strrchr() function finds the last occurrence of c (converted to a character) in string . The ending null character is considered part of the string . The strrchr() function returns a pointer to the last occurrence of c in string .

How do you get the last character of an array?

Using the split() Function of Javascipt For getting the last character of the string, we can use "" (empty character) as a delimiter and get all the characters individually in an array. Then we need to get the last element of the array. We can do that by using the array[array.


2 Answers

That is how you get the last char (which may not be what you think of as a "character"):

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

Use unwrap only if you are sure that there is at least one char in your string.


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

However, if you want to index from the end like in Python, you must do this in Rust:

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

and check if there is such a character.

If you miss the simplicity of Python syntax, you can write your own extension:

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'
}
like image 81
Boiethios Avatar answered Oct 14 '22 03:10

Boiethios


One option is to use slices. Here's an example:

let len = my_str.len();
let final_str = &my_str[len-1..];

This returns a string slice from position len-1 through the end of the string. That is to say, the last byte of your string. If your string consists of only ASCII values, then you'll get the final character of your string.

The reason why this only works with ASCII values is because they only ever require one byte of storage. Anything else, and Rust is likely to panic at runtime. This is what happens when you try to slice out one byte from a 2-byte character.

For a more detailed explanation, please see the strings section of the Rust book.

like image 37
nyghtly Avatar answered Oct 14 '22 05:10

nyghtly