Missing split_last method on &str

The slice API has a very convenient split_last method, which I am using to write some algorithms cleanly. The &str API mirrors many functions of the generic slice API, but split_last is not one of them. I found myself in need of it, so I was wondering if there was a reason for it not being present, and if not, if it could be added.

Thank you, best regards,

It couldn't be completely analogous, it could either return an Option<(&str, &str)> or an Option<(char, &str)>.

For the latter, slice_shift_char once existed (feature gated) but was removed. The deprecation advice adjusted for split_last would be:

let mut chars = s.chars();
let _ = chars.next_back().map(|c| (c, chars.as_str()));

Deprecation decided on here.

On the other hand, issue 48731 implies someone can just open a PR for a newly minted feature-gated version.

I see, as a user I think I would expect the Option<(char, &str)> version. Thanks for hinting to a PR, it looks like the way forward indeed.

Too late now, but wouldn't have

fn split_last(&self) -> Option<(&[T], &T)>

be a more logical ordering of the returned parts?

1 Like

I agree, I do not know the rationale for the current order where last is first :wink:

I would prefer split_first and split_last to have the same signature: fn(&self) -> Option<(&T, &[T])>

1 Like

Hmm... str.split_prefix/str.split_suffix?

(Pass |_| true to get char-splitting behaviour. Directly analogous to strip_prefix/strip_suffix but would potentially simplify some parsing tasks.)

(maybe also split_start_matches and split_end_matches, directly analogous to trim_start_matches and trim_end_matches?)