英文:
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"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);
}
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'));
英文:
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'0'))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论