Code Logo

Count Character

Published at24 Jul 2026
TypeScript String Handling Easy 0 views
Like0

Write a TypeScript function that counts how many times a specific character appears in a given string. The count should be case-sensitive. For example, counting 'a' in 'banana' returns 3.

Loop through each character of the string using charAt(). Compare each character with the target character. Increment a counter when they match.

Edge cases include empty strings (return 0), the character not appearing (return 0), and case-sensitive comparison where 'A' and 'a' are different.

Character counting is a basic text processing operation. The charAt() method is used instead of bracket notation for string character access, which is the safer approach in TypeScript's type system. It returns an empty string for out-of-bounds indices rather than undefined.

The comparison uses strict equality (===) which ensures case-sensitive matching. TypeScript enforces this through its type system, preventing accidental type coercion that could cause logic errors.

Edge cases include empty strings, searching for characters that don't exist, and case sensitivity where uppercase and lowercase letters are distinct.

Character counting is a basic text processing operation. The charAt() method is used instead of bracket notation for string character access, which is the safer approach in TypeScript's type system. It returns an empty string for out-of-bounds indices rather than undefined.

The comparison uses strict equality (===) which ensures case-sensitive matching. TypeScript enforces this through its type system, preventing accidental type coercion that could cause logic errors.

Edge cases include empty strings, searching for characters that don't exist, and case sensitivity where uppercase and lowercase letters are distinct. The function counts occurrences linearly, checking each character position.

Example Input & Output

Example 1
Input
"AAA", "a"
Output
0
Example 2
Input
"", "a"
Output
0
Example 3
Input
"hello", "x"
Output
0
Example 4
Input
"banana", "a"
Output
3
Example 5
Input
"hello", "l"
Output
2

Algorithm Flow

Recommendation Algorithm Flow for Count Character
Recommendation Algorithm Flow for Count Character

Solution Approach

Initialize count = 0. Loop through the string from index 0 to text.length - 1. Use text.charAt(i) to access each character. If it matches the target character, increment count. Return count.

The time complexity is O(n). Space complexity is O(1).

Best Answers

typescript - Approach 1
function countChar(text: string, char: string): number {
    var count = 0;
    for (var i = 0; i < text.length; i++) {
        if (text.charAt(i) === char) count++;
    }
    return count;
}