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.
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:
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.
Thank you for the usefull article.
NB : you have a typo between textinfo and textInfo 😉
Hi Yann. Thank you for the comment. To be honest here in searching for that typo, I found another one regarding the method name and fixed that. But since there are so many textinfo words in the article, I don’t know which one you are pointing to. Or at least I am blind enough. So, could you please point to the sentence where the typo is?
Actually it is a case typo.
You always use the variable in lower case : textinfo
But once, you defined it in camel case :
var textInfo = CultureInfo.CurrentCulture.TextInfo;
Regards,
Thank you very much, Yann. Found it.
Best Regards.
Interesting article, never even knew about ToTitleCase.