如何从`&[u8]`中提取十进制表示的数字并与整数进行比较?

huangapple go评论66阅读模式
英文:

How do I extract a number in decimal representation from a `&[u8]` and compare it with an integer?

问题

以下是翻译好的部分:

use bytes::Bytes;
use regex::bytes::Regex as BytesRegex;

fn main() {
    let val = b"2020-01-01";
    let my_regex = BytesRegex::new(r"\d{4}-(\d{2})-\d{2}").unwrap();
    let month = my_regex.captures(val).unwrap().get(1).unwrap();
    let month_digit = std::str::from_utf8(month.as_bytes()).unwrap().parse::<u8>().unwrap();
    println!("month smaller than 12: {}", month_digit <= 12);
}

你可以在这个示例中看到,我能够将捕获的组打印为无符号整数。但是,是否有一种方法可以在不转换为str的情况下获得相同的结果?

英文:

Here's an example of my code:

use bytes::Bytes;
use regex::bytes::Regex as BytesRegex;

fn main() {
    let val = b&quot;2020-01-01&quot;;
    let my_regex = BytesRegex::new(r&quot;\d{4}-(\d{2})-\d{2}&quot;).unwrap();
    let month = my_regex.captures(val).unwrap().get(1).unwrap();
    let month_digit = std::str::from_utf8(month.as_bytes()).unwrap().parse::&lt;u8&gt;().unwrap();
    println!(&quot;month smaller than 12: {}&quot;, month_digit&lt;=12);
}

https://gist.github.com/rust-play/92d4e4855015317451abad775adceec1

Like this, I was able to print out the captured group as an unsigned integer. But, I had to go via std::str::from_utf8.

Is there a way to get the same result without converting to str?

答案1

得分: 2

这可以很容易地使用 Iterator::fold 和基本的算术操作来完成:

let month_digit = month.as_bytes().iter().fold(0, |acc, c| acc * 10 + (c - b'0'));

Playground

英文:

This can be done easily with Iterator::fold and basic arithmetic:

let month_digit = month.as_bytes().iter().fold (0, |acc, c| acc*10 + (c - b&#39;0&#39;))

Playground

huangapple
  • 本文由 发表于 2023年4月13日 22:26:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76006618.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定