如何在 Rust 中从特定索引开始的子字符串中查找?

How to find in a substring starting at a specific index in Rust?

Rust 的标准库中是否有一个 find 函数可以从字符串中的给定索引开始搜索子字符串?就像 indexOf 中的 JavaScript.

您可以在 substr 上使用 str::find,然后将偏移量加回去:

let s = "foobarfoo";
let index: Option<usize> = s[4..].find("foo").map(|i| i + 4);
println!("{:?}", index);
Some(6)

我可以想到两个办法:

使用 .get() 方法安全地获取 ASCII 字符串的一部分,然后对其应用 .find

let s = "foobarfoo";
let res = s.get(4..).and_then(|s| s.find("foo").map(|i| i + 4));

使用 match_indices 遍历匹配项及其索引,然后 find_map 匹配第一个条件的索引。

let s = "foobarfoo";
let res = s.match_indices("foo").find_map(|(i, _)| (i >= 4).then(|| i));
  • 两种方法都会 return Some(6).
  • 如果索引大于或等于字符串的长度,你将 得到 None.