简体   繁体   中英

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.

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):

  • string might be empty => leads us into Option / unwrap -land
  • strings in rust are UTF-8 (which basically complicates random-accessing into string; note that rust does not only consider 0-9 as numeric, as shown here )

Starting from your original solution and parse :

fn main() {
    let a = "abc123";
    let b = "1a2b3c";
    
    println!("{:?}", a[0..1].parse::<u8>().is_ok());  // false
    println!("{:?}", b[0..1].parse::<u8>().is_ok());  // true
}

The string is guaranteed to be non empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM