Links

 

Title Casing a String in .NET using C#

When researching different ways of title casing a string in .NET using C# I came across two methods other than my own custom solution. Using Regular Expressions: This method looks at the boundary of every word, and title cases the first character after each boundary.
public static string TitleCase(string Original) { return Regex.Replace(Original, @"\b(\w)", I => I.Groups[1].Value.ToUpper()); }
Using System.Threading.Thread: Another way of using a method that specific to this problem, and also taking into account culture.
public static string TitleCase(string Original) { return Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(Original.ToLower()); }
After doing some tests with both methods, I found the Thread method to be quite faster than the regular expression method, even when the Regex was compiled. Doing 10000 title case conversions, I got the following results. Threading Method - 00:00:00.0937500 Regex Method - 00:00:00.7656250 Regex Compiled - 00:00:00.5000000
Submit a comment, suggestion, or additional information about this snippet
If you login or register, you'll be able to post a comment or provide feedback about this snippet.
Comments
That title casing method from the System.Threading.Thread class is definitely faster than my former approach to this problem. Thanks!!!
Contact Us | Terms of Use