Java
Slip18
Q.1) Write a java program that displays the number of characters, lines & words from a file. [Marks 30]
Solution
import java.io.*;
class Numchar
{
public static void main(String args[]) throws IOException
{
int ccnt=0,lcnt=1,wcnt=1,c;
FileInputStream fin=new FileInputStream("test.txt");
while((c=fin.read())!=-1)
{
System.out.print((char)c);
if(c != 13 && c != 10) //13:new line and 10:beginning of new line
ccnt++;
if(c==32 || c==13) //32-Unicode of space
wcnt++;
if(c==13) //unicode of new line(Enter)
lcnt++;
}
System.out.println("\nNumber of Characters are " + ccnt);
System.out.println("Number of Words are " + wcnt);
System.out.println("Number of Lines are " + lcnt);
fin.close();
}
}
Tags:
java