Code Logo

Capitalize First Letter

Published at25 Jul 2026
Easy 0 views
Like0

Given a string, capitalize the first character of each word. A word is defined as a sequence of characters separated by spaces. The rest of each word should remain in its original case.

Split the string into words by spaces, capitalize the first character of each word (convert to uppercase while keeping the rest unchanged), then join them back with spaces.

This is a common string manipulation task that tests string splitting, character access, and joining. Time complexity is O(n) and space complexity is O(n) for the result array and final string.

Edge cases include empty strings, single words, multiple consecutive spaces (treat each as separate), and already capitalized words.

Example Input & Output

Example 1
Input
"java"
Output
"Java"
Explanation

Single word

Example 2
Input
"hello world"
Output
"Hello World"
Explanation

Capitalize each word

Example 3
Input
"a b c"
Output
"A B C"
Explanation

Each single char word capitalized

Example 4
Input
""
Output
""
Explanation

Empty string

Example 5
Input
"HELLO"
Output
"HELLO"
Explanation

Already uppercase stays same

Algorithm Flow

Recommendation Algorithm Flow for Capitalize First Letter
Recommendation Algorithm Flow for Capitalize First Letter

Solution Approach

function solution(s) {
  if (s.length === 0) return '';
  var words = s.split(' ');
  var result = [];
  for (var i = 0; i < words.length; i++) {
    var w = words[i];
    if (w.length > 0) {
      result.push(w.charAt(0).toUpperCase() + w.slice(1));
    } else {
      result.push('');
    }
  }
  return result.join(' ');
}

Best Answers

java
class Solution {
    public String solution(String s) {
        if(s.isEmpty())return "";String[] w=s.split(" ",-1);StringBuilder r=new StringBuilder();
        for(int i=0;i<w.length;i++){
            if(!w[i].isEmpty())r.append(Character.toUpperCase(w[i].charAt(0))).append(w[i].substring(1));
            r.append(' ');
        }return r.toString().trim();
    }
}