Why TextInfo.ToTitleCase does not work correctly on a string whose letters are all in upper case?

510 views Asked by At

Could you have a look at my sample?

enter image description here

This result produces from the following example:

var str = @"VIENNA IS A VERY BEAUTIFUL CAPITAL CITY.";
var title = new CultureInfo("en-US", false).TextInfo.ToTitleCase(str.ToLower());
MessageBox.Show(title);

Because the language of the program is Turkish. I would like to draw your attention to the dotted letter I. But we all know that the right way should look like this:

Vienna Is A Very Beautiful Capital City.

How can I get the true result?

2

There are 2 answers

2
Jens On BEST ANSWER

string.ToLower has an overload that takes a CultureInfo. (Link)

Try something like

var culture = new CultureInfo("en-US", false);
var title = culture.TextInfo.ToTitleCase(str.ToLower(culture));
0
Jon Skeet On

If you want to use the US culture to perform casing, you need to do so consistently. Instead, you're currently lower-casing the string in the current culture, which is causing the problem.

Instead, use the same TextInfo for both the lower-casing and title-casing operations:

sing System;
using System.Globalization;

class Program
{
    static void Main()
    {
        CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
        var text = "VIENNA IS A VERY BEAUTIFUL CAPITAL CITY.";
        
        // Original code in the question
        var title1 = new CultureInfo("en-US", false).TextInfo.ToTitleCase(text.ToLower());
        Console.WriteLine(title1); // Contains Turkish "i" characters

        // Corrected code
        var textInfo = new CultureInfo("en-US", false).TextInfo;
        var lower = textInfo.ToLower(text);
        var title2 = textInfo.ToTitleCase(lower);
        Console.WriteLine(title2); // Correct output
    }
}

(This is broadly equivalent to Jens' answer, but I prefer to use TextInfo for both operations if you're using it for either, just for consistency.)