Count Characters
Count Characters - Explanation
Problem Summary
Write a function that counts occurrences of a specific character in a string.
Go to Problem →Detailed Explanation
이 문제는 **split의 창의적 활용**으로 특정 문자의 출현 횟수를 세는 방법을 학습합니다. **split 기반 카운팅 원리** 문자열을 특정 문자로 분할하면, 분할된 조각 수는 항상 "해당 문자 개수 + 1"입니다. **"hello"에서 "l" 카운팅** - "hello".split("l") → ["he", "", "o"] - 조각 수: 3 - "l" 개수: 3 - 1 = 2 **"banana"에서 "a" 카운팅** - "banana".split("a") → ["b", "n", "n", ""] - 조각 수: 4 - "a" 개수: 4 - 1 = 3 **왜 length - 1인가?** 구분자가 n개 있으면 문자열은 n+1개로 분할됩니다. 따라서 조각 수에서 1을 빼면 구분자 개수입니다. **대안: filter 사용** ```javascript return str.split('').filter(c => c === char).length; ``` **대안: 정규표현식** ```javascript return (str.match(new RegExp(char, 'g')) || []).length; ``` split 방법이 가장 간결하고 직관적입니다.
Solution Code
function countChar(str, char) {
return str.split(char).length - 1;
}Key Concepts from This Problem
Common Mistakes
Hints
Complexity Analysis
Time Complexity
O(n)
Grows linearly with input size
Space Complexity
O(n)
Uses memory proportional to input size