.ToTitleCase not working on all upper case string

前端 未结 3 977
旧时难觅i
旧时难觅i 2021-02-19 02:26
Public Function TitleCase(ByVal strIn As String)
      Dim result As String = \"\"
      Dim culture As New CultureInfo(\"en\", False)
      Dim tInfo As TextInfo = cult         


        
相关标签:
3条回答
  • 2021-02-19 02:54

    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());
    
    0 讨论(0)
  • 2021-02-19 02:54

    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;
    }
    
    0 讨论(0)
  • 2021-02-19 03:14

    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.

    0 讨论(0)
提交回复
热议问题