Take last N characters from string

Is there any idiomatic way to take the last N characters from String (where "character" is meant as the thing yielded by String::chars)? For now, I'm using the following:

let len = string.chars().count() - N;
string.drain(0..len).for_each(|_| {});

But this approach looks a little ugly.

This code is wrong, and may panic on non-ascii string, since the .drain() takes byte length not character count. Quick fix.

1 Like

You don't need to actually do anything with the drained items (the for_each()). The items will be removed whenever the result is dropped.

By using something like let _ = string.drain(0..len), you can explicitly say "just remove these items and throw them away".

1 Like

Oops, thanks. I looked too fast on the docs and assumed the opposite.

Thanks, that definitely looks more clear.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.