Skip to content

libcore: add str::first, str::split_first, str::last and str::split_last methods #89603

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions library/core/src/str/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,80 @@ impl str {
self.len() == 0
}

/// Returns the first character of a string slice, or [`None`] if it is
/// empty.
///
/// # Examples
///
/// ```
/// #![feature(str_first_last_char)]
/// let s = "🗻∈🌏";
/// assert_eq!(s.first_char(), Some('🗻'));
///
/// let s = "";
/// assert_eq!(s.first_char(), None);
/// ```
#[unstable(feature = "str_first_last_char", issue = "none")]
#[inline]
pub fn first_char(&self) -> Option<char> {
self.chars().next()
}

/// Returns the first character and the rest of the string slice, or
/// [`None`] if it is empty.
///
/// ```
/// #![feature(str_first_last_char)]
/// let s = "🗻∈🌏";
/// assert_eq!(s.split_first_char(), Some(('🗻', "∈🌏")));
///
/// let s = "";
/// assert_eq!(s.split_first_char(), None);
/// ```
#[unstable(feature = "str_first_last_char", issue = "none")]
#[inline]
pub fn split_first_char(&self) -> Option<(char, &str)> {
let mut iter = self.chars();
iter.next().map(|c| (c, iter.as_str()))
}

/// Returns the last character of a string slice, or [`None`] if it is
/// empty.
///
/// # Examples
///
/// ```
/// #![feature(str_first_last_char)]
/// let s = "🗻∈🌏";
/// assert_eq!(s.last_char(), Some('🌏'));
///
/// let s = "";
/// assert_eq!(s.last_char(), None);
/// ```
#[unstable(feature = "str_first_last_char", issue = "none")]
#[inline]
pub fn last_char(&self) -> Option<char> {
self.chars().next_back()
}

/// Returns the last character and the rest of the string slice, or
/// [`None`] if it is empty.
///
/// ```
/// #![feature(str_first_last_char)]
/// let s = "🗻∈🌏";
/// assert_eq!(s.split_last_char(), Some(('🌏', "🗻∈")));
///
/// let s = "";
/// assert_eq!(s.split_last_char(), None);
/// ```
#[unstable(feature = "str_first_last_char", issue = "none")]
#[inline]
pub fn split_last_char(&self) -> Option<(char, &str)> {
let mut iter = self.chars();
iter.next_back().map(|c| (c, iter.as_str()))
}

/// Checks that `index`-th byte is the first byte in a UTF-8 code point
/// sequence or the end of the string.
///
Expand Down