Adam Duffy
Posts: 168
Nickname: adamduffy
Registered: Feb, 2003
|
|
Re: Count Character Occurrence
|
Posted: Apr 17, 2003 3:02 AM
|
|
Sure thing Kevin. How about this?
import java.util.Enumeration;
import java.util.Hashtable;
public class CountChar
{
public void countEachChar( String str )
{
Hashtable hashtable = new Hashtable();
for( int i = 0; i < str.length(); i++ )
{
// get the next character in the string
Character c = new Character( str.charAt( i ) );
// check to see if the character is in the hashtable
if( hashtable.contains( c ) )
{
// get the related character occurrence count
Integer i = (Integer) hashtable.get( c );
// increment the character count
i = new Integer( i.intValue() + 1 );
// put the character count back into the hashtable
hashtable.put( c, i );
}
else
{
// add the character to the hashtable
hashtable.put( c, new Integer( 0 ) );
}
}
// print out the characters and the no of occurrences
Enumeration enum = hashtable.keys();
while( enum.hasNext() )
{
// get the next key
Character c = (Character) enum.next();
// get the related value
Integer i = (Integer) enum.get( c );
// print to display
System.out.println( c + " : " + i );
}
}
}
Adam
|
|