Drill

ProblemsC# › text

Title-case a heading

mediumtextStringsParsingC#

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

C# 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

public string TitleCase(string heading) {
    
}

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 C#
public string TitleCase(string heading) {
    var small = new HashSet<string> { "a", "an", "and", "as", "at", "but", "by", "for", "in", "of", "on", "or", "the", "to" };
    if (heading.Length == 0) return "";
    var parts = heading.Split(' ');
    for (int i = 0; i < parts.Length; i++) {
        string low = parts[i].ToLowerInvariant();
        if (i > 0 && small.Contains(low)) parts[i] = low;
        else if (low.Length == 0) parts[i] = low;
        else parts[i] = char.ToUpperInvariant(low[0]) + low.Substring(1);
    }
    return string.Join(" ", parts);
}

The same problem in another language

More text problems in C#