gpt4 book ai didi

arrays - 如何在列表的每个元素之间插入值?

转载 作者:行者123 更新时间:2023-12-04 15:56:51 25 4
gpt4 key购买 nike

这个(playground):

let s = "Hello world!";
let splitted_string = s.split_terminator("").skip(1).collect::<Vec<&str>>();
println!("splitted_string: {:?}", splitted_string);

产生以下输出:

splitted_string: ["H", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]

如何在每个元素之间插入 a 并获得类似的东西?

["H", "a", "e", "a", "l", "a", "l", "a", "o", "a", " ", "a", "w", "a", "o", "a", "r", "a", "l", "a", "d", "a", "!"]

最佳答案

已经有一个很好的 .flat_map() 答案,但是为了多样化,我们可以提供一个稍微不同的方法,我们可以使用 将多余的“a”去掉。采取():

fn main() {
let s = "Hello world!";

let interspersed = s.chars()
.flat_map(|c| [c, 'a'])
.take(s.len() * 2 - 1)
.collect::<String>();

println!("interspersed: {:?}", interspersed);
}

输出:

interspersed: "Haealalaoa awaoaralada!"

关于arrays - 如何在列表的每个元素之间插入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68623773/

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