.ToTitleCase not working on all upper case string

前端 未结 3 976
旧时难觅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

    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;
    }
    

提交回复
热议问题