count the words in a string code example
Example 1: how to count words in string
String str = "I am happy and why not
and why are you not happy and you should be";
String [] arr = str.split(" ");
Map<String, Integer> map = new HashMap<>();
for (int i=0 ; i < arr.length ; i++){
if (!map.containsKey(arr[i])){
map.put(arr[i],1);
} else{
map.put(arr[i],map.get(arr[i])+1);
}
}
for(Map.Entry<String, Integer> each : map.entrySet()){
System.out.println(each.getKey()+" occures " + each.getValue() + " times");
}
Example 2: how to count number of words in a string
String name = "Carmen is a fantastic play";
int numWords = (name.split("\\s+")).length;
System.out.println(numWords);