Capitalize First Letter
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
Single word
Capitalize each word
Each single char word capitalized
Empty string
Already uppercase stays same
Algorithm Flow
Solution Approach
Split the string, capitalize each word's first letter, lowercase the rest, and rejoin.
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
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();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
