Thursday, September 07, 2006

Capitalizing Every First Letter of Words

How would you do that in your first thought? Would you create your own user-defined function for that purpose in .NET? Please do not reinvent the wheel because there is built-in method available.

using System.Globalization;

string str = "cool strINg";
string str1 = "COOL STRING";

TextInfo objTextInfo = new CultureInfo("en-US",false).TextInfo();
str = objTextInfo.ToTitleCase(str); // Cool String *CORRECT
str1 = objTextInfo.ToTitleCase(str1); // COOL STRING *WRONG
str1 = objTextInfo.ToTitleCase(str1.toLower()); // Cool String *CORRECT

* For FULL CAPITALIZED words, you need to convert them to lower case before passing it to the ToTitleCase() method.

No comments: