string - 如何查找子字符串在给定字符串中出现的次数(包括连接)?
问题描述
联合我的意思是:
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 中做到这一点的最佳方法是什么?
解决方案
可能有更好的算法。在这里,我只是在输入字符串上移动一个具有我们正在寻找的子字符串大小的窗口,并比较该窗口是否与子字符串相同。
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);
}
推荐阅读
- sql - 我想在 case 语句中计算一个计数
- c++ - 用于 std::vector 的 std::is_copy_constructable
- c - 构建 GCC:有没有办法只构建 cpp?
- c++ - 查找数组 C++ 中出现次数最多的元素
- android - 我的 webview 在 api 级别 29 上不起作用 - 为什么?
- debugging - 可以在 VCode 的调试控制台中自动评估吗?
- excel - Excel:计算单元格范围内的字符串出现次数
- html - 如何在固定元素内添加空格?
- deep-learning - gym.spaces.box 观察状态理解
- reactjs - 与 React / Typescript 性能相关的可变范围的最佳实践是什么?