s15199d
s15199d

Reputation: 7717

.ToTitleCase not working on all upper case string

Public Function TitleCase(ByVal strIn As String)
      Dim result As String = ""
      Dim culture As New CultureInfo("en", False)
      Dim tInfo As TextInfo = culture.TextInfo()
      result = tInfo.ToTitleCase(strIn)
      Return result
 End Function

If I input "TEST" into the function above. The output is "TEST". Ideally it would output "Test"

I also tried the code snippets from this post to no avail: Use of ToTitleCase

Upvotes: 16

Views: 6387

Answers (3)

Larry
Larry

Reputation: 297

Regarding answer 1, it's a nice idea but the code does not compile; and, when corrected for syntax, it does not work. I didn't have time to debug it but you will need to if you want to use it. Part of the problem is the index assumes 1-based indexes but they are 0-based in C#. There are other issues, as well.

Upvotes: 0

Laurence
Laurence

Reputation: 1713

Also String.ToTitleCase() will work for most strings but has a problem with names like McDonald and O'Brian, and I use CurrentCulture for variations in capitalization. This is a simple extension method that will handle these:

public string ToProperCase(this string value)
{

    if (string.IsNullOrEmpty(value)) {
        return "";
    }

    string proper = System.Threading.Thread.CurrentThread.CurrentCulture.
                    TextInfo.ToTitleCase(value.ToLower());

    int oddCapIndex = proper.IndexOfAny({
        "D'",
        "O'",
        "Mc"
    });


    if (oddCapIndex > 0) {
        // recurse
        proper = proper.Substring(0, oddCapIndex + 2) +
                 proper.Substring(oddCapIndex + 2).ToProperCase();

    }

    return proper;

}

Also the IndexOfAny(String[]) extension:

public int IndexOfAny(this string test, string[] values)
{
    int first = -1;
    foreach (string item in values) {
        int i = test.IndexOf(item);
        if (i > 0) {
            if (first > 0) {
                if (i < first) {
                    first = i;
                }
            } else {
                first = i;
            }
        }
    }
    return first;
}

Upvotes: 2

Rion Williams
Rion Williams

Reputation: 76557

If memory serves, ToTitleCase() never seemed to work for all capitalized strings. It basically requires you to convert the string to lowercase prior to processing.

From the MSDN:

Generally, title casing converts the first character of a word to uppercase and the rest of the characters to lowercase. However, this method does not currently provide proper casing to convert a word that is entirely uppercase, such as an acronym.

Workaround Usage (in C#):

string yourString = "TEST";

TextInfo formatter = new CultureInfo("en-US", false).TextInfo;    
formatter.ToTitleCase(yourString.ToLower());

Upvotes: 28

Related Questions