【问题标题】:Expand (start, end) pairs in a vector在向量中展开(开始,结束)对
【发布时间】:2020-08-20 03:04:47
【问题描述】:

我有一个来自 find_iter()Vec<(usize, usize)>(开始,结束)对,我需要将其扩展为Vec<usize>。通过扩展,我的意思是[(0, 3), (10, 13)] 应该扩展为[0, 1, 2, 10, 11, 12]。所以,中间的每个数字都应该在Vec 中,从start(包括)开始,一直到end(不包括)。我有工作代码,但我想知道是否有更优雅的方法。

这是一个最小的例子:

use regex::Regex;

fn get_substring_indexes(string: &str, substring: &str) -> Vec<usize> {
    let mut indexes = Vec::new();
    for mat in Regex::new(substring).unwrap().find_iter(string) {
        indexes.extend(mat.range());
    }
    indexes
}

fn main() {
    println!("{:?}", get_substring_indexes("git add . git", "git"));
}

【问题讨论】:

    标签: loops vector rust iterator tuples


    【解决方案1】:

    Range 实现了Iterator,因此您可以将它们用作迭代器。如果您想组合和展平多个迭代器,您可以使用flatten 或在本例中为flat_map。这是您的代码的更新示例:

    playground link

    use regex::Regex;
    
    fn get_substring_indexes(string: &str, substring: &str) -> Vec<usize> {
        Regex::new(substring)
            .unwrap()
            .find_iter(string)
            .flat_map(|mat| mat.range())
            .collect()
    }
    
    fn main() {
        println!("{:?}", get_substring_indexes("git add . git", "git"));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-07
      • 2020-04-05
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 2021-04-15
      • 2021-07-25
      • 1970-01-01
      相关资源
      最近更新 更多