Count Character
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
Algorithm Flow

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
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;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
