gpt4 book ai didi

replace - 如何找到每个匹配的 byte slice 并将其替换为另一个片?

转载 作者:行者123 更新时间:2023-11-29 07:51:39 25 4
gpt4 key购买 nike

我有一个字节向量,想用 [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]);
}

Playground


示例 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]);
}

Playground

关于replace - 如何找到每个匹配的 byte slice 并将其替换为另一个片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54150353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com