Very Often we come across the 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. Recently I came across the same problem .
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 this can be done by :
Method : ToTitleCase Class: TextInfo
Namespace: System.Globalization
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(“capitalizing the first letter of some text”);
Here The CultureInfo class is from the System.Globalization namespace. From this class, you can get information about pretty much every possible culture out there, including a wide range of culture specific settings. The CultureInfo class can really help you when localizing your webpages, most notably because ASP.NET will keep a reference to the specific CultureInfo instance related to a specific visitor.
After the execution, capitalized string would have this value : “Capitalizing The First Letter Of Some Text” . which is exactly what we needed, right?
Of 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:
Suppose we want to set the current culture as of United States then,
TextInfo UsaTextInfo = new CultureInfo(“en-US”, false).TextInfo;
string capitalized = UsaTextInfo.ToTitleCase(“enjoy asp.net, enjoy coding”);
Happy Coding !!