remove a character from a string at a specific index in rust

You can use Rust's built-in string methods and chars to remove a character at a specific index in a string. Since Rust strings are UTF-8 encoded, you can't just remove a particular byte, but you have to be careful to make sure that you only remove individual characters.

One approach is to split the string into two parts around the position of the character to be removed, and then concatenate these parts back together without the unwanted character. Here's an example implementation:

main.rs
fn remove_char_at(s: &mut String, index: usize) {
    let (start, end) = s.split_at_mut(index);
    end.remove(0);
    start.push_str(end);
}
142 chars
6 lines

This function takes a mutable string slice s and an index index indicating the position of the character to remove. It splits s into a start slice and an end slice, such that the desired character is at the beginning of end. It then removes the first character of end, effectively deleting the character at the specified index. Finally, it concatenates the start and end slices to form the modified string.

Here's an example usage:

main.rs
fn main() {
    let mut s = String::from("Hello, World!");
    remove_char_at(&mut s, 7);
    println!("{}", s); // prints "Hello World!"
}
140 chars
6 lines

Note that this approach works only if the string is not empty and the index is a valid location within the string. You may want to add additional error handling to ensure that these preconditions hold.

gistlibby LogSnag