Capitalize the Title
Problem
You are given a string title made of one or more words separated by single spaces. Capitalize it: for each word, if its length is 1 or 2 make it all lowercase; otherwise make its first letter uppercase and the rest lowercase. Return the resulting title.
title = "capiTalIze tHe titLe""Capitalize The Title"def capitalize_title(title):
words = title.split(' ')
for k in range(len(words)):
w = words[k].lower()
if len(w) >= 3:
w = w[0].upper() + w[1:]
words[k] = w
return ' '.join(words)
function capitalizeTitle(title) {
const words = title.split(' ');
for (let k = 0; k < words.length; k++) {
let w = words[k].toLowerCase();
if (w.length >= 3) {
w = w[0].toUpperCase() + w.slice(1);
}
words[k] = w;
}
return words.join(' ');
}
class Solution {
public String capitalizeTitle(String title) {
String[] words = title.split(" ");
for (int k = 0; k < words.length; k++) {
String w = words[k].toLowerCase();
if (w.length() >= 3) {
w = Character.toUpperCase(w.charAt(0)) + w.substring(1);
}
words[k] = w;
}
return String.join(" ", words);
}
}
string capitalizeTitle(string title) {
string out = "";
int i = 0, n = title.size();
while (i < n) {
int j = i;
while (j < n && title[j] != ' ') j++;
for (int k = i; k < j; k++) {
char c = tolower(title[k]);
if (k == i && j - i >= 3) c = toupper(c);
out += c;
}
if (j < n) out += ' ';
i = j + 1;
}
return out;
}
Explanation
A title is just a sequence of words separated by single spaces, so the first move is to split on spaces and process each word independently, then re-join with spaces at the end.
For every word, we first normalize it to all lowercase — this wipes out whatever mixed casing the input had, like "capiTalIze".
Then the length rule decides the first letter. Words of length 1 or 2 stay entirely lowercase (think small connector words). Words of length 3 or more get their first character uppercased while the rest stay lowercase — classic title case.
We write each transformed word back into the list and finally join everything with single spaces. The C++ version does the same logic in a single pass without an explicit split, scanning word boundaries and uppercasing only the first character of words that are long enough.
Example: "capiTalIze tHe titLe". Each word has length ≥ 3, so all three are title-cased to give "Capitalize The Title".