gpt4 book ai didi

string - 如何在 Rust 中更改字符串中特定索引处的字符?

转载 作者:行者123 更新时间:2023-12-04 03:31:45 24 4
gpt4 key购买 nike

我正在尝试更改字符串中特定索引处的单个字符,但我不知道如何使用rust 。例如,如何将“hello world”中的第 4 个字符更改为“x”,使其成为“helxo world”?

最佳答案

最简单的方法是使用 replace_range() 像这样的方法:

let mut hello = String::from("hello world");
hello.replace_range(3..4,"x");
println!("hello: {}", hello);
输出: hello: helxo world ( Playground )
请注意,如果要替换的范围不在 UTF-8 代码点边界开始和结束,这将导致 panic 。例如。这会 panic :
let mut hello2 = String::from("hell😀 world");
hello2.replace_range(4..5,"x"); // panics because 😀 needs more than one byte in UTF-8
如果要替换第 n 个 UTF-8 代码点,则必须执行以下操作:
pub fn main() {
let mut hello = String::from("hell😀 world");
hello.replace_range(
hello
.char_indices()
.nth(4)
.map(|(pos, ch)| (pos..pos + ch.len_utf8()))
.unwrap(),
"x",
);
println!("hello: {}", hello);
}
( Playground )

关于string - 如何在 Rust 中更改字符串中特定索引处的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66661118/

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