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
Go 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
func titleCase(heading string) string {
}
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 Go
func titleCase(heading string) string {
small := map[string]bool{"a": true, "an": true, "and": true, "as": true, "at": true, "but": true, "by": true, "for": true, "in": true, "of": true, "on": true, "or": true, "the": true, "to": true}
if heading == "" {
return ""
}
parts := strings.Split(heading, " ")
for i, w := range parts {
low := strings.ToLower(w)
if i > 0 && small[low] {
parts[i] = low
} else if low == "" {
parts[i] = low
} else {
parts[i] = strings.ToUpper(low[:1]) + low[1:]
}
}
return strings.Join(parts, " ")
}