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

2024-03-12

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


最简单的方法是使用replace_range() https://doc.rust-lang.org/std/string/struct.String.html#method.replace_range像这样的方法:

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

Output: 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

如果你想替换第 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);
}

()

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐