Home » Bit Hacks(bits,nibbles&bytes) » Count Characters FromFile

Count Characters FromFile


import java.io.*;

import java.util.*;

class CountCharactersFromFile {
 public static void main(String[] args) throws Exception {
 BufferedReader br = new BufferedReader(new FileReader("data.txt"));
 String strLine = "";
 String str = "";
 while ((strLine = br.readLine()) != null) {
 str += strLine;
 }
 String st = str.replaceAll(" ", "").toLowerCase();
 char[] third = st.toCharArray();

 System.out.println("Character Total");

 for (int counter = 0; counter < third.length; counter++)
 {
 char ch = third[counter];
 int count = 0;

 /// n*n complexity its a brute forc approach..

 for (int i = 0; i < third.length; i++) {
 if (ch == third[i])
 count++;
 }

 /// this for loop is used to avoid repeation
 boolean b = true;


 for (int j = counter - 1; j >= 0; j--) {
 if (ch == third[j]) /// if ch already present set it true
 b = false;
 }

 if (b) { // if not present prveviously then print, else dont print
 System.out.println(ch + " " + count);
 }
 }
 }
}

 


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: