如何从Rust迭代器提取首尾元素?(AoC2023 Day1代码优化)
Advent of Code 2023 第1天任务优化问题
这是《Advent of Code 2023》第1天任务的一部分,需求是提取字符串中的数字字符,取首尾字符后转换为整数。目前已有可正常运行的代码:
fn main() { let line = "treb7uchet"; // 筛选所有数字字符 let v: String = line .chars() // 过滤数字字符 .filter(|c| c.is_numeric() ) // 仅筛选第一个元素的尝试(已注释) // .enumerate() // .filter(|&(i, _)| i == 0) // .map(|(_, e)| e) .collect::<String>(); // println!("{}", v); // 获取首尾数字并转换为整数 let my_int: i32 = format!("{}{}", v.chars().nth(0).unwrap(), v.chars().last().unwrap()) .parse() .unwrap(); println!("{}", my_int); } // 输出结果:77
这段代码能正常运行,但我希望把逻辑合并成一行实现。我试过用enumerate(代码中已注释),但它只能过滤出第一个元素,想了解如何同时过滤出最后一个元素,或者Rust迭代器有没有直接提取首尾元素的方法?
内容的提问来源于stack exchange,提问作者Winston
相关产品推荐
相关产品推荐

