Contents

About implementing character counting (with.Java)

   Sep 13, 2023     3 min read

In this article, we looked at implementing character counting (with.Java).

We’ll be solving a coding test problem, reflecting on the problem we solved, and learning about other ways to solve it.

Let’s start with the problem

Problem

Given a string my_string that contains only alphabetical characters.

count of β€˜A’ in my_string, count of β€˜B’ in my_string,…, count of β€˜Z’ in my_string, count of β€˜a’ in my_string, count of β€˜b’ in my_string,…

Write a solution function that returns an array of integers of length 52 containing the number of occurrences of β€˜z’ in my_string in order.

Example input and output

my_string: β€œProgrammers”

result: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 0, 1, 0, 0, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0]

In my_string, there is one β€˜P’, one β€˜a’, one β€˜e’, one β€˜g’, two β€˜m’, one β€˜o’, three β€˜r’, and one β€˜s’, so.

returns [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 2, 0, 1, 0, 0, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0].

My solution to the problem

class Solution {
    public int[] solution(String my_string) {
        int[] answer = new int[52];
        for (int i = 0; i < my_string.length(); i++) {
            char c = my_string.charAt(i);

            if (c >= 'A' && c <= 'Z') {
                answer[c - 'A']++;
            } else if (c >= 'a' && c <= 'z') {
                answer[26 + c - 'a']++;
            }
        }

        return answer;
    }
}
Solution

This code counts the frequency of occurrence of alphabetical characters within the given string my_string.

The result is returned as an array of int[], where each element of the array represents the number of occurrences of a particular alphabetical character.

The answer array is an integer array of length 52, storing counts for the uppercase and lowercase letters of the alphabet, respectively.

Indexes 0 through 25 store the number of occurrences of the uppercase letters β€˜A’ through β€˜Z’.

Indexes 26 through 51 store the number of occurrences of lowercase letters β€˜A’ through β€˜Z’.

Here’s how the code works:

Iterate over the length of my_string, checking for each letter c.

If c is an uppercase letter, subtract β€˜A’ to find the position of that uppercase letter, and increment the count at that position. (answer[c - β€˜A’]++)

If c is a lowercase letter, subtract β€˜a’ and add 26 to find the corresponding lowercase letter and increment the count at that position. (answer[26 + c - β€˜a’]++)

When it has finished processing all the characters, it returns an array of answer. This array represents the number of occurrences of each letter of the alphabet in the string.