Home > front end >  How to split a string into the first character and the rest?
How to split a string into the first character and the rest?

Time:03-27

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?

CodePudding user response:

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()..]))
}

CodePudding user response:

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()))
}
  • Related