04 May 2008 @ 7:23 PM 
 

How to count the frequency of the same characters in a string

 


1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5 out of 5)
Loading ... Loading ...
771 views

Here’s a demo I made that counts the frequency/occurences in a given string. Took me an hour or so to write it but it was fun to do so on a boring sunday. It also counts a few special character such as spaces and brackets etc.

Sourcecode:

import java.util.ArrayList;
import java.util.Vector;
public class StringCount {
public static void main(String[] args) {
StringCount SC = new StringCount();
SC.usage();
SC.countCharacters(”www.engineeringserver.com is a site for (student) software developers, especially Java developers that want to know more about Java and Java development in general.”);
}
public void countCharacters(String input){
String[] alphabet = {”a”,”b”,”c”,”d”,”e”,”f”,”g”,”h”,”i”, “j”, “k”, “l”, “m”,
“n”,”o”, “p”, “q”, “r”, “s”, “t”,”u”,”v”,”w”,”x”,”y”,”z”, ” “, “[","]“,”‘”,”,”, “/”,”\\”,”:”,”.”,”-”,”(”,”)”};
System.out.println(”Input: ” + input);
System.out.println();
ArrayList occurences = new ArrayList();
int times = 0;
for (int i = 0; i< alphabet.length; i++){
for (int k = 0; k < input.length(); k++){
if(alphabet[i].equals(”" + input.toLowerCase().charAt(k))){
times++;
}
}
occurences.add(alphabet[i] + ” found\t” + times + ” times”);
times = 0;
}
for(int i = 0; i< occurences.size(); i++){
System.out.println(occurences.get(i));
}
}
public void usage(){
System.out.println(”By: HappyFace - www.engineeringserver.com :: v1.0 initial release”);
}
}

Output:

By: HappyFace - www.engineeringserver.com :: v1.0 initial release
Input: www.engineeringserver.com is a site for (student) software developers, especially Java developers that want to know more about Java and Java development in general.

a found 14 times
b found 1 times
c found 2 times
d found 5 times
e found 22 times
f found 2 times
g found 3 times
h found 1 times
.. etc

Download the sourcecode here: http://www.freefilehost.co.uk/902604
Password: engineeringserver.com

Related posts

Your Ad Here
Tags Tags: ,
Categories: Java
Posted By: HappyFace
Last Edit: 14 May 2008 @ 11 52 AM

EmailPermalink
 

Responses to this post » (None)

 

Post a Comment

You must be logged in to post a comment.

\/ More Options ...
Change Theme...
  • Users » 888
  • Posts/Pages » 1,444
  • Comments » 506
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

Online Users



    No Child Pages.

Forum



    No Child Pages.