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

rus*_*100 17 string char rust

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

HHK*_*HHK 19

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

let mut hello = String::from("hello world");
hello.replace_range(3..4,"x");
println!("hello: {}", hello);
Run Code Online (Sandbox Code Playgroud)

输出hello: helxo world:(游乐场

请注意,如果要替换的范围不在 UTF-8 代码点边界上开始和结束,这将会发生混乱。例如这会恐慌:

let mut hello2 = String::from("hell world");
hello2.replace_range(4..5,"x"); // panics because  needs more than one byte in UTF-8
Run Code Online (Sandbox Code Playgroud)

如果你想替换第 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);
}
Run Code Online (Sandbox Code Playgroud)

游乐场