Count words using two vectors
- Given a string that consists of words and white-spaces, count how many times each word appears!
- In this solution we use two vectors. A much better solution would be to use HashMap, but in this example I wanted to show the solution with two vectors.
- One vector will hold the list of distinct words.
- The second vector will hold the count for each word.
examples/vectors/count-words/src/main.rs
fn main() { let text = "mouse cat cat oliphant"; let parts = text.split_whitespace(); let mut words:Vec<&str> = vec![]; let mut count:Vec<i32> = vec![]; for word in parts { let mut found = false; for ix in 0..words.len() { if words[ix] == word { count[ix] += 1; found = true; break; } } if ! found { words.push(word); count.push(1); } } // report for ix in 0..words.len() { println!("{}: {}", words[ix], count[ix]) } }
mouse: 1 cat: 2 oliphant: 1