diff --git a/examples/word_counter/README.md b/examples/word_counter/README.md index d213460211..1316ad8b2d 100644 --- a/examples/word_counter/README.md +++ b/examples/word_counter/README.md @@ -1,24 +1,25 @@ ``` usage: word_counter [text_file] using cinderella.txt +a => 25 able => 2 -afterwards => 1 after => 1 -against => 2 +afterwards => 1 again => 10 -allowed => 2 -allow => 1 +against => 2 all => 12 +allow => 1 +allowed => 2 along => 1 also => 2 always => 2 +an => 4 and => 140 anew => 1 anger => 1 another => 2 answered => 1 -anyone => 2 any => 1 -an => 4 +anyone => 2 ... ``` diff --git a/examples/word_counter/word_counter.v b/examples/word_counter/word_counter.v index 26bdbd45eb..d6c0b951c1 100644 --- a/examples/word_counter/word_counter.v +++ b/examples/word_counter/word_counter.v @@ -18,12 +18,8 @@ fn main() { return } mut m := map[string]int - for word in contents.to_lower().split(' ') { - key := filter_word(word) - if key == '' { - continue - } - m[key] = m[key] + 1// TODO m[key]++ + for word in extract_words(contents) { + m[word] = m[word] + 1 // TODO m[key]++ } // Sort the keys mut keys := m.keys() @@ -35,6 +31,30 @@ fn main() { } } +// Creates an array of words from a given string +fn extract_words(contents string) []string { + mut splitted := []string + for space_splitted in contents.to_lower().split(' ') { + if space_splitted.contains('\n') { + splitted << space_splitted.split('\n') + } + else { + splitted << space_splitted + } + } + + mut results := []string + for s in splitted { + result := filter_word(s) + if result == '' { + continue + } + results << result + } + + return results +} + // Removes punctuation fn filter_word(word string) string { if word == '' || word == ' ' {