Prepin
Log in

A

Create a program that counts the occurrences of each character in a specified text file.

Approach / Explanation

This task requires you to develop a program that counts how many times each character appears in a specified text file. You should read the file, analyze its content one character at a time, and maintain a cumulative count for each character. Important aspects to keep in mind include: Grasping the file reading method in the programming language you select to tackle the task. Navigating through the text file character by character. Tallying the frequency of each character. Considering case sensitivity (i.e., deciding whether to treat 'a' and 'A' as identical or distinct characters).

Suggested Answer

If we are utilizing Python, the collections.Counter() function can be employed to tally the occurrences of each character. Here’s one way to achieve this: import collections def count_chars ( file_name ) : with open ( file_name , 'r' ) as file : text = file . read ( ) count = collections . Counter ( text ) return count In this case, collections.Counter() will automatically determine the frequency of each character in the file. We begin by opening the file, reading its contents, and saving that content to a variable. Afterward, we compute the frequency of each character and return the result.

Alternative Answer

Here’s a Java example: import java . io . FileReader ; import java . util . HashMap ; import java . util . Map ; public class CharacterCounter { public static void main ( String [ ] args ) { Map < Character , Integer > frequency = new HashMap < > ( ) ; try ( FileReader file = new FileReader ( "textfile.txt" ) ) { int character ; while ( ( character = file . read ( ) ) != - 1 ) { char c = ( char ) character ; frequency . put ( c , frequency . getOrDefault ( c , 0 ) + 1 ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } for ( Map . Entry < Character , Integer > entry : frequency . entrySet ( ) ) { System . out . println ( entry . getKey ( ) + " : " + entry . getValue ( ) ) ; } } } This Java program starts by initializing an empty HashMap to track the frequency of each character. It uses a FileReader to read the text file one character at a time. The file.read() method retrieves the ASCII value of each character, which is then cast to a character ( (char) character ) and the count in the map is incremented by one ( frequency.put(c, frequency.getOrDefault(c, 0) + 1) ). If the character is not already in the map, it initializes to 0 before increasing to 1. Finally, the program outputs the count for each character.

Question Details

Difficulty & Category

Medium
technical

Companies

Andela

Product

AI Candidate AgentCompaniesBrowse JobsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin | All rights reserved.