4

I have a program like this

public class no_of_letters_count {
static int i;
 public static void main(String[] args) 
 {

  String sMessage="hello how r u";
  String saMessage[] = sMessage.split("");
  List sList = Arrays.asList(saMessage);                  
  Collections.sort(sList);
  Iterator i=sList.iterator();
  while (i.hasNext())
  {
   System.out.println((String)i.next());
  }
 }
}

//Now i want to count the number of occurance of each characters.

Like

Count of h=2

Count of e=1

and so on

3
  • Can you reformat your post so it looks better? Commented Feb 1, 2010 at 12:31
  • 7
    As you see new answers to your question, vote up the helpful ones by clicking the upward pointing arrow to the left of your question (...) When you have decided which answer is the most helpful to you, mark it as the accepted answer by clicking on the check box outline to the left of the answer. This lets other people know that you have received a good answer to your question. Doing this is helpful because it shows other people that you're getting value from the community. (If you don't do this, people will often politely ask you to go back and accept answers for more of your questions!) Commented Feb 1, 2010 at 12:39
  • 1
    And to find/read all questions you previously asked, click anywhere where your nickname appears as a link so that you land in your profile page: stackoverflow.com/users/175023/gourav The questions are listed there (note: they may be spread over several pages). Commented Feb 1, 2010 at 13:31

4 Answers 4

4

Iterate over sList and put each char in a HashMap. If it doesn't exists start with count 1, otherwise increment the count.

EDIT : Cannot help posting some code.

First of all, use gnerics.

List<Character> sList = Arrays.asList(saMessage.toCharArray()); 

Then use the following map :

Map<Character, Integer> cmap = new HashMap<Character, Integer>();
Sign up to request clarification or add additional context in comments.

1 Comment

I was going to post it, but I won't now :)
1

Using commons-collections and commons-lang

List<Character> chars = Arrays.asList(
     ArrayUtils.toObject("asdfasdas".toCharArray()));
Bag bag = new HashBag(chars);

System.out.println(bag.getCount('a'));

4 Comments

do you really need Appache-Commons to count the letters? its just a homework
why not? you just add 2 libraries and write 2 lines. If it were my homework, I'd do it this way. On the other hand - yes, it's not the point
In most homework assignments it's stipulated that you must implement the core algorithm yourself rather than import it from a library like this. It's probably okay (but overkill) to use it to iterate over the string, but not to use an off-the-shelf bag/multiset implementation.
it wasn't stipulated in the question :) Anyway, I agree this is missing the point of it being a homework. But since the point is already lost after asking for a solution on SO.. in addition, he will probably have headaches adding the libraries to the classpath, which is again a good learning experience
0

Prints number of occurrences of characters from A-Z and a-z

Note: using the character as array index, not safe if you have Unicode chars :), but still good idea i think!!

String str = "sometext anything";
int[] array=new int[256];

for (int x:array) array[x]=0;

for (char c:str.toCharArray()){
    array[c]++;
}

for (int i=65;i<=90; i++){
    System.out.println("Number of "+(char)i+ "="+array[i]
                + ", number of "+(char)(i+32)+"="+ array[i+32]);
}

2 Comments

If you're not interested in characters with 0 occurances then why not just use a map where the key is the character... Instead of an array of mostly zeros.
i know, but its just a homework and i wanted to show the simplest way (i guess)
0

Here are some hints:

It seems you are just trying to get the chars in a String. Use String.toCharArray().

Use a Map<Character,Integer> to store the chars and it's occurrences:

foreach char c in sMessage.ToCharArray()
if map.containsKey(c)
  map.put(c, map.get(c) + 1);
else
  map.put(c, 1);

Next sort the map and present the results. I leave you here a snippet to sort the map:

    List<Entry<Character,Integer>> l = new ArrayList<Entry<Character,Integer>>(map.entrySet());

    Collections.sort(l, new Comparator<Entry<Character,Integer>>() {
        public int compare(Entry<Character, Integer> o1, Entry<Character, Integer> o2) {
            return o1.getKey().compareTo(o2.getKey());
        }
    });

1 Comment

Why not just use a SortedMap to avoid the overhead of the additional sort? Also, you can avoid calling containsKey(c) by calling get(c) and assigning the result to an Integer, and comparing this against null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.