remove a character from a string in rust

To remove a character from a Rust string, you can first convert the string to a vector of characters, remove the desired character from the vector, and then convert the vector back to a string. The following function demonstrates this approach:

main.rs
fn remove_char(input: &str, c: char) -> String {
    let mut chars: Vec<char> = input.chars().collect();
    chars.retain(|&x| x != c);
    let result: String = chars.into_iter().collect();
    result
}
203 chars
7 lines

This function takes two arguments: the input string and the character to be removed. It first converts the input string into a vector of characters using the chars method. It then uses the retain method on the vector to remove all occurrences of the desired character. Finally, it converts the modified vector back into a string using the collect method.

Here's an example of how you can use this function:

main.rs
fn main() {
    let input = "hello world";
    let result = remove_char(input, 'l');
    println!("{}", result); // prints "heo word"
}
136 chars
6 lines

Note that this function only removes the first occurrence of the character. If you want to remove all occurrences of the character, you can modify the function to use a loop and the remove method on the vector.

gistlibby LogSnag