The Artima Developer Community
Sponsored Link

Java Answers Forum
Character Occurrence using arrays

5 replies on 1 page. Most recent reply: Apr 23, 2003 5:38 PM by Matt Gerrans

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 5 replies on 1 page
Kevin

Posts: 27
Nickname: quasi
Registered: Apr, 2003

Character Occurrence using arrays Posted: Apr 23, 2003 4:25 AM
Reply to this message Reply
Advertisement
How do I display the occurence of each character in a string so that no character is repeated when printed using two arrays (1:keep track of letter 2:store occurrence)?
Expected out is
NAME: JOHNNY
CHARACTER COUNT
J: 1 O: 1 H:1 N:2 Y:1
Any help would be great


Dhrubo

Posts: 32
Nickname: dhrubo
Registered: Mar, 2003

Re: Character Occurrence using arrays Posted: Apr 23, 2003 7:53 AM
Reply to this message Reply
class TestString
{


public static void main(String args[])
{
String strSample = new String("YJOHNNYY");
int intCharCount = strSample.length();
char chrStore[] = strSample.toCharArray() ;
int intOccurance[] = new int[intCharCount];
for(int p = 0 ; p< intCharCount ; p++)
intOccurance[p] = 0 ;

char chTemp = ' ';
for(int i = 0 ; i < intCharCount ; i++)
{
chTemp = chrStore;

if(intOccurance != -1)
{
System.out.print(chTemp+":");
intOccurance = 0;
for(int j = i ; j < intCharCount ; j++)
{

if(chTemp == chrStore[j])
{
intOccurance = intOccurance + 1;

if(intOccurance > 1)
{
intOccurance[j] = -1 ;
}//if
}//if

}//for
System.out.print(intOccurance+" ");
}//if
}//for

}//main

}//TestString

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: Character Occurrence using arrays Posted: Apr 23, 2003 12:25 PM
Reply to this message Reply
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 );
   }
}

Jaycee

Posts: 26
Nickname: jaycee
Registered: Apr, 2003

Re: Character Occurrence using arrays Posted: Apr 23, 2003 3:38 PM
Reply to this message Reply
Why use arrays? Do this instead:

import java.util.*;

public class StringOGram{

public static void main(String args[]) throws Exception{
String string = "HelloWorld";

char[] chars = string.toCharArray();
HashMap frequency = new HashMap();
Integer count;

for(int i=chars.length-1; i>=0; i--){
Character character = new Character(chars);
count = (Integer)frequency.get(character);

if(count==null){
frequency.put(character, new Integer(0));
}else{
frequency.put(character, new Integer(count.intValue()+1));
}
}

Iterator iter = frequency.keySet().iterator();
Object charKey;
System.out.println("NAME: "+string);
System.out.println("CHARACTER COUNT");
while(iter.hasNext()){
charKey = iter.next();
System.out.print(charKey+" :"+frequency.get(charKey)+" ");
}
System.out.println();
}
}

Jaycee

Posts: 26
Nickname: jaycee
Registered: Apr, 2003

Re: Character Occurrence using arrays Posted: Apr 23, 2003 3:39 PM
Reply to this message Reply
without bug:

import java.util.*;

public class StringOGram{

public static void main(String args[]) throws Exception{
String string = "HelloWorld";

char[] chars = string.toCharArray();
HashMap frequency = new HashMap();
Integer count;

for(int i=chars.length-1; i>=0; i--){
Character character = new Character(chars);
count = (Integer)frequency.get(character);

if(count==null){
frequency.put(character, new Integer(1));
}else{
frequency.put(character, new Integer(count.intValue()+1));
}
}

Iterator iter = frequency.keySet().iterator();
Object charKey;
System.out.println("NAME: "+string);
System.out.println("CHARACTER COUNT");
while(iter.hasNext()){
charKey = iter.next();
System.out.print(charKey+" :"+frequency.get(charKey)+" ");
}
System.out.println();
}
}

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: Character Occurrence using arrays Posted: Apr 23, 2003 5:38 PM
Reply to this message Reply
As I mentioned before there there was a another solution previously posted to this forum that uses a Map, but I think the array constraint stems from the fact that this is probably a homework assignment where the instructor said to use an array. Maybe doing it with a Map will be a subsequent exercise -- in that case Kevin can come right back here for the follow-up homework solution.

By the way, if you put [java] tags around your code when you post, it comes out with the indentation intact and syntax coloring added.

Flat View: This topic has 5 replies on 1 page
Topic: Please if you know "What is Java Byte Code Previous Topic   Next Topic Topic: balanced parenthesis function

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use