首页 > 解决方案 > 如何查找子字符串在给定字符串中出现的次数(包括连接)?

问题描述

联合我的意思是:

let substring = "CNC";

和字符串:

let s = "CNCNC";

在我的版本中,“jointed”意味着存在2这样的子字符串。这样做的最好方法是什么Rust?我能想到一些,但它基本上是丑陋的C

我有类似的东西:

fn find_a_string(s: &String, sub_string: &String) -> u32 {
    s.matches(sub_string).count() as u32
}

但那又回来了1,因为matches()只发现脱节substrings

在 Rust 中做到这一点的最佳方法是什么?

标签: stringalgorithmrust

解决方案


可能有更好的算法。在这里,我只是在输入字符串上移动一个具有我们正在寻找的子字符串大小的窗口,并比较该窗口是否与子字符串相同。

fn main() {
    let string = "aaaa";
    let substring = "aa";

    let substrings = string
        .as_bytes()
        .windows(substring.len())
        .filter(|&w| w == substring.as_bytes())
        .count();

    println!("{}", substrings);
}

推荐阅读