Title-case a heading
The CMS title-cases headings on save, but the house style leaves the small joining words in lowercase unless one of them opens the heading.
- Capitalise the first letter of every word and lowercase the rest of it.
- These stay lowercase: a, an, and, as, at, but, by, for, in, of, on, or, the, to.
- Except the very first word, which is always capitalised.
- Words are separated by single spaces.
titleCase(heading: string) → string
Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
String titleCase(String heading) {
}
Worked examples
| Call | Result |
|---|---|
titleCase("the lord of the rings") | "The Lord of the Rings" |
titleCase("a tale OF two cities") | "A Tale of Two Cities" |
titleCase("hello") | "Hello" |
titleCase("of mice and men") | "Of Mice and Men" |
Hint
Handle index 0 as its own case, then let the small-word list decide for the rest.
Reference solution in Java
String titleCase(String heading) {
Set<String> small = new HashSet<>(Arrays.asList("a", "an", "and", "as", "at", "but", "by", "for", "in", "of", "on", "or", "the", "to"));
if (heading.isEmpty()) return "";
String[] parts = heading.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
if (i > 0) sb.append(' ');
String low = parts[i].toLowerCase();
if (i > 0 && small.contains(low)) sb.append(low);
else if (low.isEmpty()) sb.append(low);
else sb.append(Character.toUpperCase(low.charAt(0))).append(low.substring(1));
}
return sb.toString();
}