How to remove duplication in a vector in rust

i tried using

use std::{iter::Inspect, str};
fn main() {
    let mut Inp: String = String::from("jsjnkns");
    let mut str: &str = &Inp;
    let mut  chr: Vec<char> = Inp.chars().collect::<Vec<_>>();
    for mut x in chr.iter_mut(){
         x.count==1;{
        println!("numbers: {:?}", &x);
    }
       
}
}

i want it to retun me "jsnk"

Please edit your post to follow our syntax highlighting guidelines:

use std::collections::HashSet;

fn remove_duplicates(mut s: String) -> String {
    let mut seen = HashSet::new();
    s.retain(|c| {
        let is_first = !seen.contains(&c);
        seen.insert(c);
        is_first
    });
    s
}
1 Like

can you please quote this with an example string like "shdshsds"

I would be happy to help you further once you have fixed your original post.

hope its comfortable now

You are using the wrong character. It should be a backtick or tilde character, not a period.

check out now

Alright, give this a try:

use std::collections::HashSet;

fn remove_duplicates(mut s: String) -> String {
    let mut seen = HashSet::new();
    s.retain(|c| {
        let is_first = !seen.contains(&c);
        seen.insert(c);
        is_first
    });
    s
}

fn main() {
    println!("{}", remove_duplicates(String::from("shdshsds")));
}

yeah it did.. thanks alot

You can also exploit the return value of the HashSet::insert() which is a bool.

fn remove_duplicates(mut s: String) -> String {
    let mut seen = HashSet::new();
    s.retain(|c| seen.insert(c));
    s
}
6 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.