.NET method to convert a string to sentence case

后端 未结 9 1726
一向
一向 2020-11-30 09:47

I\'m looking for a function to convert a string of text that is in UpperCase to SentenceCase. All the examples I can find turn the text into TitleCase.

<
9条回答
  •  抹茶落季
    2020-11-30 10:13

    There is a built in ToTitleCase() function that will be extended to support multiple cultures in future.

    Example from MSDN:

    using System;
    using System.Globalization;
    
    public class Example
    {
       public static void Main()
       {
          string[] values = { "a tale of two cities", "gROWL to the rescue",
                              "inside the US government", "sports and MLB baseball",
                              "The Return of Sherlock Holmes", "UNICEF and children"};
    
          TextInfo ti = CultureInfo.CurrentCulture.TextInfo;
          foreach (var value in values)
             Console.WriteLine("{0} --> {1}", value, ti.ToTitleCase(value));
       }
    }
    // The example displays the following output:
    //    a tale of two cities --> A Tale Of Two Cities
    //    gROWL to the rescue --> Growl To The Rescue
    //    inside the US government --> Inside The US Government
    //    sports and MLB baseball --> Sports And MLB Baseball
    //    The Return of Sherlock Holmes --> The Return Of Sherlock Holmes
    //    UNICEF and children --> UNICEF And Children
    

    While it is generally useful it has some important limitations:

    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. The following table shows the way the method renders several strings.

    ...the ToTitleCase method provides an arbitrary casing behavior which is not necessarily linguistically correct. A linguistically correct solution would require additional rules, and the current algorithm is somewhat simpler and faster. We reserve the right to make this API slower in the future.

    Source: http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx

提交回复
热议问题