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.
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)