Sunday, November 25, 2012

How to Capitalize the First Letter of All Words in a string in C#

Often we need to capitalize the first letters of some word or some text (for example when we want to display users name or city name etc).
Since string class does not have a method to do this we could think that there is no built-in solution in C# for this problem...

But a little digging trough MSDN would help us find ToTitleCase method of TextInfo class in System.Globalization namespace that does exactly what we need: capitalizes the first letter of each word in the string.

here is how to use it:

using System.Globalization;


...


string capitalized = CultureInfo.CurrentCulture.TextInfo.ToTitleCase("asp.net simply rocks!!!");

After the execution, capitalized string would have this value: "Asp.Net Simply Rocks!!!" which is exactly what we needed, right?

Off course, how will string be capitalized depends on the current culture that is set on your ASP.NET page, but we can easily override this and use the culture we want like this:

TextInfo UsaTextInfo = new CultureInfo("en-US", false).TextInfo;
string capitalized = UsaTextInfo.ToTitleCase("asp.net simply rocks!!!");

Have fun!

=======================================================
For more Books / Ads / Lost-Found / Articles / Accommodation. We can help with your busy lifestyle. Take a look around and review our hundreds of free Ads or submit one of your own favorites. http://www.inhousetoday.com

No comments: