Home > DeveloperSection > Blogs > Find the Frequency of a sentence

Find the Frequency of a sentence


Java Java 
Ratings:
0 Comment(s)
 1916  View(s)
Rate this:

Find the Frequency of a sentence

In this blog I am trying to make a small demo which is count the frequency of a sentence accepted by user using java.

import java.nio.CharBuffer;

import java.nio.MappedByteBuffer;

import java.nio.channels.FileChannel;

import java.nio.charset.Charset;

import java.nio.charset.CharsetDecoder;

import java.util.Map;

import java.util.TreeMap;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import java.util.LinkedHashMap;

import java.util.Scanner;

public class WordFreq

{

                public static void main(String args[]) throws Exception

                {

                                Scanner in = new Scanner(System.in);

                                System.out.print("Enter String : ");

                        String text=in.nextLine();

                text = text.replaceAll("( )+", " ");

                                wordFrequencyCount(text);

                }

                public static void wordFrequencyCount(String s)

{

    int count=0;

    String sentance[]=sortWords(s);

    System.out.println("Word\t\tfrequency");

    for(int i=0;i<sentance.length;)

    {

        count=1;

        for(int index=i+1;index<sentance.length;index++)

        {

            if(sentance[i].compareTo(sentance[index])==0)

            {

                               

                count++;

            }

            else

            {

                break;

            }

        }

               

      

        System.out.println(""+sentance[i] +"\t\t"+count);

               

        i+=count;

    }

 

}

public static String[] sortWords(String s1)

{

    String s[]=s1.split(" ");

    for( int i=0;i<s.length-1;i++)

        {

            for( int j=0;j<s.length-i-1;j++)

            {

                if(s[j].compareTo(s[j+1])>0)

                {

                    String g=s[j+1];

                    s[j+1]=s[j];

                    s[j]=g;

                }

            }      

        }

    return s;

}

}


Output: -


Don't want to miss updates? Please click the below button!

Follow MindStick