Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net-core

The .NET Framework has a method TextInfo.ToTitleCase.

Is there something equivalent in .NET Core?

Edit: I'm looking for a built-in method in .NET Core.

like image 433
Andreas Bilger Avatar asked Jul 13 '16 20:07

Andreas Bilger


2 Answers

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.

like image 115
mxmissile Avatar answered Sep 20 '22 03:09

mxmissile


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

like image 39
Andreas Bilger Avatar answered Sep 18 '22 03:09

Andreas Bilger