how to find occurrence of words in string

Solutions on MaxInterview for how to find occurrence of words in string by the best coders in the world

showing results for - "how to find occurrence of words in string"
Han
02 Jul 2018
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} 
Evan
23 Nov 2016
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    }
similar questions
queries leading to this page
how to find occurrence of words in string