stringrust

Simpler way to check if string start with a digit in Rust?


What I am currently using is this

fn main() {
    let a = "abc123";
    let b = "1a2b3c";

    println!("{}", a[0..1].chars().all(char::is_numeric));
    println!("{}", b[0..1].chars().all(char::is_numeric));
}

Are there a more idiomatic and/or simpler way to do this?

Note: The string is guaranteed to be non empty and made of ASCII characters.


Solution

  • If you are sure that it is non-empty and made out of ascii, you can operate directly on bytes (u8):

    a.as_bytes()[0].is_ascii_digit()
    

    or

    (b'0'..=b'9').contains(&a.as_bytes()[0])
    

    More general setting (and, in my opinion, more idiomatic):

    a.chars().next().unwrap().is_numeric()
    

    The reason all this looks a bit unwieldy is that there may be some things going wrong (that are easily overlooked in other languages):