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);
}
}
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