How to count the occurrence of each character in char array?

15,660

Solution 1

Here is a relatively straightforward method using Java 8 streams

Character[] charArray = new Character[1000];
IntStream.rand(0, charArray.length)
    .forEach(n -> charArray[n] = randomCharacter());
Map<Character, Long> charCountMap = Arrays.stream(charArray)
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting());

This leaves you with a map from each character to the number of times it occurs in the array.

Forget efficiency unless you are processing billions of characters a second or you are trying to run it on a digital watch from the 90s.

Solution 2

Let's say you're only concerned with English alphabetic characters. The char type in Java is really an integer, so you can use a for loop to loop over ranges, e.g.

for( char c='a'; c<='z'; c++) {
   for( char x : chararry ) {
        if( c == x ) {
           // increment your counter for 'c'
        }
   }
}

Use a similar loop for upper case charcters.

Now it's just a matter of where to store your counters. I'd suggest using an array where each index in the array corresponds to one of your character values. You could write a pretty simple method to translate an ASCII character value to an index between 0-51 for an array.

Share:
15,660
KingKrypton
Author by

KingKrypton

Updated on July 20, 2022

Comments

  • KingKrypton
    KingKrypton almost 2 years

    I'm trying to count the occurrence of each character in an char array. How many times a specific lower case or upper case letter appears? What would be an effective method as I keep running in circles and into errors?

    This is the code I used to populate the array with random characters:

    char[] chararray = new char[1000]; 
       for (int i = 0; i < chararray.length; i++) { 
           char c = randomCharacter();
           chararray[i] = c;  
       }//end for  
    

    I've tried creating a second array to count it for both upper and lower case such as, but I'm not sure what to do with it:

    int[] counter = new int[52];
    

    Any sort of help would be appreciated it. Thank you.