Count the words in a string using java program

Counting words of string using java is a easy using HashMap, where key will become words and value will become number of occurrence of the word, if word already available in the HashMap so increase the value with 1 else add a new word with value 1.



import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class WordCount {

public static void main(String[] args) {

Scanner scn =new Scanner(System.in);
System.out.println("Type string to cound the words");
String s = scn.nextLine();

Map map = wordCount(s);

System.out.println(map);
}

public static Map wordCount(String s) {

Map map = new HashMap();

String[] str = s.split(" |,|\\.");// or(|) for multiple parameter for split
for (int i = 0; i < str.length; i++) {

if (map.containsKey(str[i])) {
map.put(str[i], (Integer) map.get(str[i]) + 1);
} else {
map.put(str[i], 1);
}
}
return map;
}

}

Post a Comment

Previous Post Next Post