Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: Character Occurrence using arrays
|
Posted: Apr 23, 2003 12:25 PM
|
|
Here's a modification of an answer to a previous homework assignment, which I think does what you want.
You can also search for this forum for a version that uses Maps, which is probably a more flexible, general and sensible way to solve this problem.
/*
* CharCountHomework.java
*
* Simple demo of yet another letter-histogram homework assignment.
*
* Copyright 2003, Matt Gerrans.
*
* Turning in this code as homework is a violation of ethical principals,
* and punishable by severe penalties, even if you change the variable
* names.
*/
class CharCountHomework
{
/**
* Returns the "histogram" of characters for the String.
*/
public static int [] getCharProfile( String s )
{
int [] results = new int[26];
for( int i = 0; i < s.length(); i++ )
if( Character.isLetter(s.charAt(i)) )
results[(int)(Character.toLowerCase(s.charAt(i))-'a')]++;
return results;
}
/**
* Prints the list of character frequencies in the specified
* string to the specified PrintStream destination.
*/
public static void printProfile( String text, java.io.PrintStream destination )
{
int [] profile = getCharProfile(text);
destination.println( "Profile of \"" + text + "\":" );
for( int i = 0; i < profile.length; i++ )
destination.print( (i>0?", ":"") +(char)('a'+i) + ":" + profile[i] );
destination.println(".");
}
/**
* Assembles all the separate parts of the command line arguments
* array into one String and returns it.
*
* If the args array is empty, it just returns
* "The quick brown fox jumps over the lazy dog"
* which is a pretty handy string for test input.
*/
public static String assembleCommandLineText(String args[])
{
String text = "The quick brown fox jumps over the lazy dog";
if( args.length > 0 )
{
StringBuffer buffy = new StringBuffer( args[0] );
for( int i = 0; i < args.length; i++ )
{
buffy.append( " " );
buffy.append( args[i] );
}
text = buffy.toString();
}
return text;
}
/**
* Prints (to System.out) out a profile of the letters a test string.
* The stirng could be specified on the command line, but if
* nothing is specified, the default string will suffice.
*/
public static void main(String args[])
{
printProfile( assembleCommandLineText(args), System.out );
}
}
|
|