java - how do i count occurrence of words in a line -
i new java. want count occurrences of words in particular line. far can count words no idea how count occurrences.
is there simple way this?
scanner file = new scanner(new fileinputstream("/../output.txt")); int count = 0; while (file.hasnextline()) { string s = file.nextline(); count++; if(s.contains("#avfc")){ system.out.printf("there %d words on line ", s.split("\\s").length-1); system.out.println(count); } } file.close();
output:
there 4 words on line 1 there 8 words on line 13 there 3 words on line 16
simplest way can think of use string.split("\\s")
, split based on spaces.
then have hashmap
containing word key value being number of times used.
hashmap<string, integer> mapofwords = new hashmap<string, integer>(); while (file.hasnextline()) { string s = file.nextline(); string[] words = s.split("\\s"); int count; (string word : words) { if (mapofwords.get(word) == null) { mapofwords.put(word, 1); } else { count = mapofword.get(word); mapofwords.put(word, count + 1); } } }
implementation requested skip strings contain words
hashmap<string, integer> mapofwords = new hashmap<string, integer>(); while (file.hasnextline()) { string s = file.nextline(); string[] words = s.split("\\s"); int count; if (isstringwanted(s) == false) { continue; } (string word : words) { if (mapofwords.get(word) == null) { mapofwords.put(word, 1); } else { count = mapofword.get(word); mapofwords.put(word, count + 1); } } } private boolean isstringwanted(string s) { string[] checkstrings = new string[] {"chelsea", "liverpool", "#lfc"}; (string check : checkstring) { if (s.contains(check)) { return false; } } return true; }
Comments
Post a Comment