Re-Format Strings to Title Case in C#

I was just working on a small project that was importing data into one system from another. The data in the source system was formatted using all-caps, but the data entry practice for the destination system was to enter values using mixed or title case.

No problem, right? Reformatting the string values seems like a reasonably simple task. Make the whole thing lowercase, then capitalize the first letter. Improve the solution by using regular expressions to capitalize letters that follow spaces and hyphens.

But hold on a sec! It turns out it’s even easier than that. The .NET Framework has a culture-basedĀ TextInfo class that has a ToTitleCase method. Nice–way to have exactly what I need, Microsoft!

var textInfo = CultureInfo.CurrentCulture.TextInfo;
return textInfo.ToTitleCase(value);

ToTitleCase will format each word in a string to title case, with the first letter uppercase and subsequent letters lowercase. It respects whitespace as a word boundary as well as certain punctuation, such as commas, periods, question marks, and exclamation points. It’s not title case in the strictest sense since all words–including prepositions, articles, and conjunctions–will be capitalized, but it’s definitely good enough to satisfy my needs. The algorithm assumes words in all-caps are abbreviations or acronyms and ignores them, but you can get around that by using string‘s ToLower method.

Here are a few example uses:

Console.WriteLine(textInfo.ToTitleCase("hello, world!"));
Console.WriteLine(textInfo.ToTitleCase("this and that"));
Console.WriteLine(textInfo.ToTitleCase("words.with.periods"));
Console.WriteLine(textInfo.ToTitleCase("WORDS WITH ALL CAPS"));
Console.WriteLine(textInfo.ToTitleCase("WORDS WITH ALL CAPS (TOLOWER EDITION)".ToLower()));

// Output:
//    Hello, World!
//    This And That
//    Words.With.Periods
//    WORDS WITH ALL CAPS
//    Words With All Caps (Tolower Edition)
Advertisement

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: