如何检查字符是ASCII数字还是句点?

我想检查单个char是 ASCII 数字 ( '1' - '9') 还是句点 ( '.')。在 Rust 中做到这一点的最佳方法是什么?我知道这is_digit(10)是针对数字的,但我该如何针对数字或句点 ( .) 执行此操作?

回答

一个小问题char::is_numeric可能是它匹配的不仅仅是 ASCII 0..=9,例如:

'½'.is_numeric() == true

还有char::is_ascii_digit,如果你只是想匹配ASCII 0..=9

后者是用matches!宏实现的。您还可以将宏用于您的用例,例如:

if matches!(c, '0'..='9' | '.') {
  // Character is ASCII digit '0' up to and including '9' or '.'
}

  • This is actually a very elegant solution, which I didn't think of.

回答

使用is_numericOR'd 进行'.'相等检查:

fn is_numeric_or_period(c: char) -> bool {
    char::is_numeric(c) || c == '.'
}

注意:is_numeric匹配所有数字 unicode 字符,并且与is_ascii_digitASCII 字符串的行为相同,但如果您正在使用 unicode 字符串并且只想匹配 ASCII 数字字符,请参阅@Jason 的答案。


以上是如何检查字符是ASCII数字还是句点?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>