In this article, we are going to learn how to convert string to title case in C#. In the title case, the first character of a word is the uppercase letter, while the remaining characters are in lowercase.

To download the source code for this article, you can visit our GitHub repository.

Let’s dive in.

Using ToTitleCase Method to Convert String to Title Case in C#

C# has an inbuilt TextInfo.ToTitleCase() method that we can use to convert strings to title case:

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

public string ToTitleCase (string str);

This method exists within System.Globalization namespace. However, TextInfo.ToTitleCase() cannot convert words that are entirely in uppercase to title case. We will see how to do that later on.

To use the ToTitleCase() method, we first need to create a TextInfo:

var textinfo = new CultureInfo("en-US", false).TextInfo;

As you can see, we create a TextInfo based on the “en-US” culture. We can also use the culture of our current location when declaring the TextInfo instance:

var textinfo = CultureInfo.CurrentCulture.TextInfo;

Afterward, we can call ToTitleCase() and convert our desired string to a title case:

Console.WriteLine(textinfo.ToTitleCase("a tale oF tWo citIes"));

Console.WriteLine(textinfo.ToTitleCase("harry potter and the Deathly hallows"));

Converting an Entire Uppercase String to Title Case

As we said earlier, ToTitleCase() cannot convert words that are entirely uppercase such as acronyms. To convert such words, we have to parse the string as lowercase:

Console.WriteLine(textinfo.ToTitleCase("OLIVER TWIST".ToLower()));

Furthermore, it is worth mentioning that ToTitleCase method is not linguistically correct. Compared to our previous examples, the linguistically correct outcome would be:

A Tale of Two Cities

Harry Potter and the Deathly Hallows

Nonetheless, ToTitleCase() is a simpler and faster way of converting strings to title cases.

Conclusion

In this article, we have learned how we can convert strings to title cases in C# using the TextInfo.ToTitleCase() method. We’ve also learned how to convert the all-uppercase strings to title-case strings. 

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!