To replace a character at a specific index in a string in Rust, you need to convert the string to a mutable byte array and then directly modify the byte at the desired index.
In this example,
str
.as_bytes_mut()
.index
with the byte representation of the character newChar
.str
.fn main() {
let mut str = String::from("Hello World");
let index = 6;
let new_char = b'x';
let bytes = str.as_bytes_mut();
bytes[index] = new_char;
println!("{}", str);
}
Hello xorld
In this tutorial, we learned How to Replace Character at Specific Index in String in Rust language with well detailed examples.