Code Logo

Capitalize First Letter

Published at25 Jul 2026
Easy 3 views
Like0

Given a string of words separated by spaces, capitalize the first letter of each word and make the rest of each word lowercase. Return the transformed string.

For example, "hello world" becomes "Hello World". "JAVA SCRIPT" becomes "Java Script". "aN eXaMpLe" becomes "An Example". An empty string returns "".

Title casing is a common text formatting operation used in names, titles, headings, and proper nouns. It tests string splitting, character manipulation, and rejoining.

The solution splits the string into words, processes each word by capitalizing the first character and lowercasing the rest, then joins the words back with spaces.

Edge cases include an empty string (return ""), a single word (capitalize first letter), words with apostrophes or hyphens (each part is treated as a separate word if split by spaces), and leading/trailing spaces.

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

Solution Approach

Split the string, capitalize each word's first letter, lowercase the rest, and rejoin.

function capitalizeWords(s)
  words = split(s, " ")
  for i = 0 to length(words) - 1
    w = words[i]
    if length(w) > 0
      words[i] = uppercase(w[0]) + lowercase(substring(w, 1))
  return join(words, " ")

Split the input on spaces. For each non-empty word, take the first character and convert it to uppercase, then take the remainder of the word and convert it to lowercase. Join the processed words back with single spaces.

Time complexity is O(n), space complexity is O(n).

Best Answers

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