How to remove characters present in first string from the second string in Rust

2 Answers

0 votes
use std::collections::HashSet;

/// Removes all characters from `source` that appear in `chars_to_remove`.
fn remove_characters(source: &str, chars_to_remove: &str) -> String {
    let forbidden: HashSet<char> = chars_to_remove.chars().collect();

    source
        .chars()
        .filter(|c| !forbidden.contains(c))
        .collect()
}

fn main() {
    let first = "programming language";
    let second = "rogy";

    let result = remove_characters(second, first);

    println!("First : {:?}", first);
    println!("Second: {:?}", second);
    println!("Result: {:?}", result);
}


/*
run:

First : "programming language"
Second: "rogy"
Result: "y"

*/

 



answered Oct 4 by avibootz
0 votes
use std::collections::HashSet;

/// Removes all characters from `source` that appear in `chars_to_remove`.

fn remove_characters(source: &str, chars_to_remove: &str) -> String {
    let forbidden: HashSet<char> = chars_to_remove.chars().collect();
    let mut result = String::with_capacity(source.len());

    for ch in source.chars() {
        if !forbidden.contains(&ch) {
            result.push(ch);
        }
    }

    result
}

fn main() {
    let first = "programming language";
    let second = "rogy";

    let result = remove_characters(second, first);

    println!("First : {:?}", first);
    println!("Second: {:?}", second);
    println!("Result: {:?}", result);
}


/*
run:

First : "programming language"
Second: "rogy"
Result: "y"

*/

 



answered Oct 4 by avibootz

Related questions

...