replace a character in a string in rust

To replace a single character in a Rust string, you can use the replace() method with the old and new characters as arguments. Here is an example:

main.rs
let mut my_string = String::from("hello world");

// replace the first 'l' with 'L'
if let Some(index) = my_string.find('l') {
    my_string.replace_range(index..index+1, "L");
}

assert_eq!(my_string, "heLlo world");
218 chars
9 lines

In this example, we first find the index of the first occurrence of the letter 'l' using the find() method. We then use the replace_range() method to replace the character at that index with the new character. Finally, we assert that the resulting string is the expected value of "heLlo world". Note that we had to use mut to make my_string mutable since replace_range() modifies the original string.

gistlibby LogSnag