最简单的方法是使用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);
}
()