Calculating frequency of each word in a sentence in java

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

    You could try this

    public static void frequency(String s) {
        String trimmed = s.trim().replaceAll(" +", " ");
        String[] a = trimmed.split(" ");
        ArrayList p = new ArrayList<>();
        for (int i = 0; i < a.length; i++) {
            if (p.contains(i)) {
                continue;
            }
            int d = 1;
            for (int j = i+1; j < a.length; j++) {
                if (a[i].equals(a[j])) {
                    d += 1;
                    p.add(j);
                }
            }
            System.out.println("Count of "+a[i]+" is:"+d);
        }
    }
    

提交回复
热议问题