📜

Capitalize String

Capitalize String - Explanation

쉬움 문자열 O(n) O(n)

Problem Summary

Write a function that capitalizes the first letter of a string.

Go to Problem →

Detailed Explanation

이 문제는 **문자열 분리**와 **대소문자 변환**을 결합하여 첫 글자만 대문자로 만드는 방법을 학습합니다. **핵심 전략: 분리 후 결합** 1. 첫 글자: str[0] 2. 나머지: str.slice(1) 3. 결합: 대문자 첫 글자 + 나머지 **"hello" 처리 과정** - str[0] → "h" - "h".toUpperCase() → "H" - str.slice(1) → "ello" - "H" + "ello" → "Hello" **빈 문자열 처리** 빈 문자열에서 str[0]은 undefined입니다. 이 경우 에러를 방지하기 위해 먼저 체크합니다: `if (!str) return str;` **toUpperCase()의 특성** 이미 대문자인 경우에도 에러 없이 그대로 반환합니다: "H".toUpperCase() → "H" **slice(1)의 특성** - 빈 문자열에서 slice(1)은 빈 문자열 반환 - 한 글자에서 slice(1)도 빈 문자열 반환 **대안: charAt(0)** `str[0]` 대신 `str.charAt(0)`도 사용할 수 있습니다. 빈 문자열에서 charAt(0)은 빈 문자열을 반환합니다.

Solution Code

solution.js
function capitalize(str) {
  if (!str) return str;
  return str[0].toUpperCase() + str.slice(1);
}

Key Concepts from This Problem

1. toUpperCase 메서드
2. slice 메서드
3. 문자열 인덱싱
4. 빈 문자열 처리

Common Mistakes

빈 문자열에서 str[0]이 undefined임을 처리해야 합니다
slice(1)을 잊으면 첫 글자만 반환됩니다
원본 문자열은 변경되지 않으므로 결과를 반환해야 합니다

Hints

Hint 1: 첫 글자와 나머지를 분리하세요.

Complexity Analysis

Time Complexity

O(n)

Grows linearly with input size

Space Complexity

O(n)

Uses memory proportional to input size

Related Tags

#문자열 #toUpperCase #slice