How do you find duplicate characters in a given string in Rust
Rust
x
18
fn main() {
let mut s = String::new();
println!("Enter a string: ");
std::io::stdin().read_line(&mut s).expect("Failed to read line");
let mut chars = HashMap::new();
for c in s.chars() {
if c == ' ' { continue; }
let count = chars.entry(c).or_insert(0);
*count += 1;
}
for (c, count) in &chars {
if *count > 1 { println!("{}: {}", c, count); }
}
}
🤖 Code Explanation
The code creates a mutable string, reads in a line from standard input, and stores the characters of that string in a hashmap. The hashmap keeps track of how many times each character appears in the string. Finally, the code prints out any characters that appear more than once in the string.