BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 1.1+

Convert a String to Title Case

Text can be converted to entirely upper case or lower case using standard methods from the String class. Another common format is title case, where the first letter of each word is usually capitalised. This case can be applied using the TextInfo class.

TextInfo Class

The TextInfo class is used to define the rules within a particular writing system, culture or language. This includes the rules for conversion of a string between cases such as upper, lower and title case. As these rules that are dependent upon the user's local settings or upon a locale specified in code, TextInfo is found in the System.Globalization namespace.

using System.Globalization;

The TextInfo class does not have a public constructor. Instead, an instance of the class must be retrieved from the TextInfo property of a CultureInfo object. An ideal CultureInfo object to use in a Windows Forms application is the user's selected, or current culture. The following command obtains the TextInfo object for the current culture.

TextInfo info = CultureInfo.CurrentCulture.TextInfo;

To perform the conversion to title case, the ToTitleCase method of the TextInfo class is used. The method requires a single parameter containing the string to be formatted. It returns the updated string. In most cases, the new string will have a capital letter for the initial letter of each word and all other letters will be lower case. If a word is already capitalised, this will generally remain as upper case. However, the rules are determined by the selected culture and may differ between languages.

To try the conversion, executed the following:

string sample = "The quick brown fox JUMPS over the lazy dog.";
Console.WriteLine(info.ToTitleCase(sample));

// Outputs "The Quick Brown Fox JUMPS Over The Lazy Dog."

NB: The output shown is based upon UK formatting. The results may vary according to your local settings.

30 September 2008