Calculating frequency of each word in a sentence in java

前端 未结 19 2090
夕颜
夕颜 2020-11-29 10:15

I am writing a very basic java program that calculates frequency of each word in a sentence so far i managed to do this much

import java.io.*;

class Linked         


        
19条回答
  •  死守一世寂寞
    2020-11-29 11:06

    Created a simple easy to understand solution for this problem covers all test cases-

    import java.util.HashMap;
    import java.util.Map;
    
    /*
     * Problem Statement - Count Frequency of each word in a given string, ignoring special characters and space 
     * Input 1 - "To be or Not to be"
     * Output 1 - to(2 times), be(2 times), or(1 time), not(1 time)
     * 
     * Input 2 -"Star 123 ### 123 star"
     * Output - Star(2 times), 123(2 times)
     */
    
    public class FrequencyofWords {
    
        public static void main(String[] args) {
            String s1="To be or not **** to be! is all i ask for";
            fnFrequencyofWords(s1);
            
        }
        
        //-------Supporting Function-----------------
        static void fnFrequencyofWords(String s1) {
            //------- Convert String to proper format----
            s1=s1.replaceAll("[^A-Za-z0-9\\s]","");
            s1=s1.replaceAll(" +"," ");
            s1=s1.toLowerCase();
            
            //-------Create String to an array with words------
            String[] s2=s1.split(" ");
            System.out.println(s1);
                
            //-------- Create a HashMap to store each word and its count--
            Map  map=new HashMap();
            for(int i=0;i

提交回复
热议问题