Monday, October 22, 2012

Word,character count in Java

Program  to count the number of occurrences of a word in a file is given as below:


import java.io.*;

class wordcnt
{
  public static void main(String args[])
  {
    int i = 0,cnt = 0;
    try
    {
      FileInputStream fin = new FileInputStream("d:/java/wordcnt.java");
      String word;
      char ch , charr[];
      charr = new char[100];
      String w = new String("word");
      while(( ch = (char)fin.read()) != -1)
      {
        if( ch != ' ' && ch != '\n')
        {
           charr[i] = ch ;
           i++;
        }
        else
        {
           word = new String(charr,0,i);
           if(word.equals(w))
              cnt++;   
           if( ch == '\n')
              System.out.println( word );
           else
              System.out.print( word + " ");
           i = 0;
        }
     };
     fin.close();
    }
    catch(Exception ie)
    {
    }
    System.out.println("\n\nWord Count : " + cnt);
  }
}

No comments:

Post a Comment

MS SQL : How to identify fragmentation in your indexes?

Almost all of us know what fragmentation in SQL indexes are and how it can affect the performance. For those who are new Index fragmentation...