[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

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

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

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.