Word Count
Word Count - Explanation
Problem Summary
Write a function that counts the number of words in a string.
Go to Problem →Detailed Explanation
이 문제는 **split()과 정규표현식**을 사용하여 단어 개수를 세는 방법을 학습합니다. ## 핵심 개념: 문자열 분리와 카운팅 문자열을 단어로 분리한 후 배열의 길이를 구합니다. ### 접근 방법 ```javascript str.trim().split(/\s+/).length ``` 1. trim(): 양 끝 공백 제거 2. split(/\s+/): 하나 이상의 공백으로 분리 3. length: 배열 길이 = 단어 수 ### 정규표현식 \s+ - \s: 공백 문자 (스페이스, 탭, 줄바꿈 등) - +: 하나 이상 ```javascript "hello world".split(" ") // ["hello", "", "", "world"] "hello world".split(/\s+/) // ["hello", "world"] ``` ### 빈 문자열 처리 ```javascript "".split(/\s+/) // [""] - 길이 1! "".trim().split(/\s+/) // [""] - 여전히 1! ``` 빈 문자열은 별도 처리가 필요합니다: ```javascript if (!str.trim()) return 0; ``` 단어 카운팅은 텍스트 분석의 기본입니다.
Solution Code
function wordCount(str) {
if (!str.trim()) return 0;
return str.trim().split(/\s+/).length;
}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