In python you can get the last 5 characters of a string like this:
s[-5:]
How do you do the same concisely in Rust? The best I could figure out was extremely verbose:
s.chars().rev().take(5).collect::<Vec<_>>().into_iter().rev().collect()
In python you can get the last 5 characters of a string like this:
s[-5:]
How do you do the same concisely in Rust? The best I could figure out was extremely verbose:
s.chars().rev().take(5).collect::<Vec<_>>().into_iter().rev().collect()
Using char_indices
let s = "Hello, World!";
let last_five = {
let split_pos = s.char_indices().nth_back(4).unwrap().0;
&s[split_pos..]
};
assert_eq!("orld!", last_five);
If you need to do this operations very often, consider to use UTF-32 encoding. To convert string to UTF-32, you need to do this: let utf_32: Vec<char> = s.chars().collect()
. In such case you can do &utf_32[utf_32.len()-5..]
.