ToTitleCase
This C# method makes each word in a string
title case—it capitalizes each word in a string
. No custom code is needed to call ToTitleCase
.
You could develop character-based algorithms to accomplish this goal. But the System.Globalization
namespace provides ToTitleCase
, which can be simpler.
Consider a simple string
in C# like "purple fish." The string
has 2 words separated with a space. Each word should have an uppercase letter.
purple fish -> Purple Fish
This program shows how to call ToTitleCase
. To access CultureInfo
, you need to include the System.Globalization
namespace. The input here is "purple fish."
using System; using System.Globalization; class Program { static void Main() { string value = "purple fish"; string titleCase = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(value); Console.WriteLine(titleCase); } }Purple Fish
When should ToTitleCase
be used? Programs often have edge cases. A custom implementation can provide better support for certain words.
We looked at the ToTitleCase
method on the TextInfo
type. ToTitleCase
can simplify your program, but it cannot be easily customized.