首页 > 解决方案 > 如何更改 rust 字符串中特定索引处的字符?

问题描述

我正在尝试更改字符串中特定索引处的单个字符,但我不知道如何生锈。例如,我如何将“hello world”中的第 4 个字符更改为“x”,这样它就变成了“helxo world”?

标签: stringrustchar

解决方案


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

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

输出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);
}

游乐场


推荐阅读