Drill

ProblemsGo › text

Title-case a heading

mediumtextStringsParsingGo

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.

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.

Solve it in Python →

Where you start

func titleCase(heading string) string {
	
}

Worked examples

CallResult
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, " ")
}

The same problem in another language

More text problems in Go