Built-in method to convert a string to title case in .NET Core?

Unfortunately, still in October 2016, .NET Core does not provide us with a ToTitleCase method.

I created one myself that works for my own needs. You can adjust it by adding your own delimiters to the regular expressions. Replace _cultureInfo with the CultureInfo instance that is applicable to you.

public static class TextHelper
{
     private static readonly CultureInfo _cultureInfo = CultureInfo.InvariantCulture;

     public static string ToTitleCase(this string str)
     {
         var tokens = Regex.Split(_cultureInfo.TextInfo.ToLower(str), "([ -])");

         for (var i = 0; i < tokens.Length; i++)
         {
             if (!Regex.IsMatch(tokens[i], "^[ -]$"))
             {
                 tokens[i] = $"{_cultureInfo.TextInfo.ToUpper(tokens[i].Substring(0, 1))}{tokens[i].Substring(1)}";
             }
         }

         return string.Join("", tokens);
     }
 }

It seems there is no such method built-in to .NET Core.


You can implement your own extension method:

public static class StringHelper
{
    public static string ToTitleCase(this string str)
    {
        var tokens = str.Split(new[] { " ", "-" }, StringSplitOptions.RemoveEmptyEntries);
        for (var i = 0; i < tokens.Length; i++)
        {
            var token = tokens[i];
            tokens[i] = token == token.ToUpper()
                ? token 
                : token.Substring(0, 1).ToUpper() + token.Substring(1).ToLower();
        }

        return string.Join(" ", tokens);
    }
}

Credit: blatently copied form this gist*.

*Added the bit for acronyms Dotnet Fiddle.


.NET Standard 2.0 added TextInfo.ToTitleCase (source), so you can use it in .NET Core 2.0.

For .NET Core 1.x support, however, you are out of luck.

Tags:

C#

.Net Core