1function countOccurences(str,word)
2{
3 // split the string by spaces in a
4 String a[] = str.split(",");
5
6 // search for pattern in a
7 int count = 0;
8 for (int i = 0; i < a.length; i++)
9 {
10 // if match found increase count
11 if (word.equals(a[i]))
12 count++;
13 }
14
15 return count;
16}
1HOW TO COUNT OCCURRENCE OF THE WORDS IN STRING
2(It can also be solved by using nested for loops...)
3
4String str = "I am happy and why not and why are you not happy you should be";
5 String [] arr = str.split(" ");
6 Map<String, Integer> map = new HashMap<>();
7
8 for (int i=0 ; i < arr.length ; i++){
9 if (!map.containsKey(arr[i])){
10 map.put(arr[i],1);
11 } else{
12 map.put(arr[i],map.get(arr[i])+1);
13 }
14 }
15 for(Map.Entry<String, Integer> each : map.entrySet()){
16
17 System.out.println(each.getKey()+" occures " + each.getValue() + " times");
18 }