简体   繁体   English

检查字符串是否以 Rust 中的数字开头的更简单方法?

[英]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.注意:字符串保证为非空且由 ASCII 字符组成。

If you are sure that it is non-empty and made out of ascii, you can operate directly on bytes ( u8 ):如果您确定它是非空的并且由 ascii 制成,则可以直接对字节( 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字符串可能为空 => 引导我们进入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 ) rust 中的字符串是 UTF-8 (这基本上使随机访问字符串变得复杂;注意 rust不仅将 0-9 视为数字,如此处所示

Starting from your original solution and parse :从您的原始解决方案开始并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.该字符串保证为非空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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