Convert a string to proper case (title case) in C#

[proper case]

In proper case (or title case) the first letter of each word is capitalized. This is actually pretty easy once you know where to find the method that converts to proper case.

The example uses the following code to convert the string in the variable txt into proper case.

// Convert to proper case.
CultureInfo culture_info = Thread.CurrentThread.CurrentCulture;
TextInfo text_info = culture_info.TextInfo;
txt = text_info.ToTitleCase(txt);

The code creates a CultureInfo object representing the program’s current culture. (This uses the System.Globalization and System.Threading namespaces.) It gets the culture’s TextInfo object and calls its ToTitleCase method to convert the text to proper case.

Note that this method isn’t perfect. For example, it will keep a string in all caps such as NASA in all caps but it won’t preserve odd mixed case examples such as VBScript. It also doesn’t consider an apostrophe to be the start of a new word so, for example, it would capitalize the name O’Dell as O’dell. Those are odd cases, however, and I wouldn’t expect it to handle every case perfectly.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in strings and tagged , , , , , , , , , , , . Bookmark the permalink.

1 Response to Convert a string to proper case (title case) in C#

  1. Dwight Kurt Schrute III says:

    Bless you Sir,
    This is by far the simplest solution ive seen.

    Many Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.