Calculating frequency of each word in a sentence in java

前端 未结 19 2068
夕颜
夕颜 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:13

    Try this

    public class Main
    {
    
        public static void main(String[] args)
        {       
            String text = "the quick brown fox jumps fox fox over the lazy dog brown";
            String[] keys = text.split(" ");
            String[] uniqueKeys;
            int count = 0;
            System.out.println(text);
            uniqueKeys = getUniqueKeys(keys);
    
            for(String key: uniqueKeys)
            {
                if(null == key)
                {
                    break;
                }           
                for(String s : keys)
                {
                    if(key.equals(s))
                    {
                        count++;
                    }               
                }
                System.out.println("Count of ["+key+"] is : "+count);
                count=0;
            }
        }
    
        private static String[] getUniqueKeys(String[] keys)
        {
            String[] uniqueKeys = new String[keys.length];
    
            uniqueKeys[0] = keys[0];
            int uniqueKeyIndex = 1;
            boolean keyAlreadyExists = false;
    
            for(int i=1; i

    Output:

    the quick brown fox jumps fox fox over the lazy dog brown
    Count of [the] is : 2
    Count of [quick] is : 1
    Count of [brown] is : 2
    Count of [fox] is : 3
    Count of [jumps] is : 1
    Count of [over] is : 1
    Count of [lazy] is : 1
    Count of [dog] is : 1
    

提交回复
热议问题