我有一个字节向量,想用 [4, 5, 6]
替换每个 [1, 2, 3]
。这在 Rust 中怎么可能?
let mut buf = vec![1, 2, 3, 7, 8];
// ?
assert_eq!(buf, vec![4, 5, 6, 7, 8]);
最佳答案
这个函数可以完成这个工作:
fn replace_slice<T>(source: &mut [T], from: &[T], to: &[T])
where
T: Clone + PartialEq,
{
let iteration = if source.starts_with(from) {
source[..from.len()].clone_from_slice(to);
from.len()
} else {
1
};
if source.len() > from.len() {
replace_slice(&mut source[iteration..], from, to);
}
}
此函数是递归的,但您也可以使用循环重写它。
示例 1:
fn main() {
let mut buf = vec![1, 2, 3, 7, 8, 1, 2, 3];
replace_slice(&mut buf[..], &[1, 2, 3], &[4, 5, 6]);
assert_eq!(buf, vec![4, 5, 6, 7, 8, 4, 5, 6]);
}
示例 2: (来自 trentcl 的评论)
fn main() {
let mut buf = vec![1, 2, 3, 3, 4, 1, 2, 3];
replace_slice(&mut buf[..], &[1, 2, 3], &[5, 1, 2]);
assert_eq!(buf, vec![5, 1, 2, 3, 4, 5, 1, 2]);
}
关于replace - 如何找到每个匹配的 byte slice 并将其替换为另一个片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54150353/