OneBite.Dev - Coding blog in a bite size

Remove A Character From A String In Rust

Code snippet for how to Remove A Character From A String In Rust with sample and detail explanation

Rust is a highly efficient system programming language that guarantees the safety of concurrent programs and preserves the high-level models of abstraction. One of the common operations in any programming language including Rust is removing a specific character from a string or a given text.

Code snippet for Removing a Character From A String

Below is a quick code snippet to remove a character from a string in Rust:

fn remove_character(s: &str, c: char) -> String {
    s.chars().filter(|&x| x != c).collect()
}

fn main() {
    let test_string = "Hello, World!";
    let result_string = remove_character(&test_string, 'l');
    println!("{}", result_string);
}

In this code, when you run remove_character(&test_string, 'l');, it will print Heo, Word! by removing all occurrences of ‘l’.

Code Explanation for Removing a Character From A String

In the above Rust program, we start by defining a function named remove_character(s: &str, c: char) -> String.

This function takes in two parameters:

  • A reference to a string s from which we want to remove characters.
  • A character c which we want to remove from the string.

Within the function, s.chars().filter(|&x| x != c).collect(), we convert the string to chars using the chars() method. We then filter all characters x that do not equal the requested char c using the filter method.

After filtering all the characters that are not equal to c, we collect them back into a string using the collect() method. This new string does not have any occurrence of the removed character, which is returned by the function as the end result.

The main function is the entry point of our Rust program. We define a string test_string and call our remove_character() function with test_string and the char ‘l’. The result is then printed to the console. You can change ‘l’ to any character you desire to remove from your given string.

So, this is how you can remove a specific character from a string in Rust. Remember, Rust is case-sensitive, so ensure you watch out for uppercase and lowercase characters when using this function.

rust