How to split a string into the first character and the rest?

Viewed 332

This is the code I currently have:

fn split_first_char(s: &str) -> Option<(char, &str)> {
    let mut char_indices = s.char_indices();
    let (_, c) = char_indices.next()?;
    let i = match char_indices.next() {
        Some((i, _)) => i,
        None => s.len(),
    };
    Some((c, s.split_at(i).1))
}

Is there an easier or built-in way to do the same?

3 Answers

I found another more elegant solution:

fn split_first_char(s: &str) -> Option<(char, &str)> {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) => Some((c, chars.as_str())),
        None => None,
    }
}

or

fn split_first_char(s: &str) -> Option<(char, &str)> {
    let mut chars = s.chars();
    chars.next().map(|c| (c, chars.as_str()))
}

I don't think so, but you can make this lot shorter:

fn split_first_char(s: &str) -> Option<(char, &str)> {
    s.chars().next().map(|c| (c, &s[c.len_utf8()..]))
}

Since Rust 1.50 you can use split_first()

"My String".chars().collect::<Vec<char>>().split_first();

This results in:

Option<(&char, &[char])>

While the type isn't exactly Option<(char, &str)> it may be close enough to what you are looking for.

Related