How to convert string to title case in C#?

CsharpServer Side ProgrammingProgramming

Title case is any text, such as in a title or heading, where the first letter of major words is capitalized. Title case or headline case is a style of capitalization used for rendering the titles of published works or works of art in English.When using title case, all words are capitalized except for "minor" words unless they are the first or last word of the title.

The current implementation of the ToTitleCase in the example yields an output string that is the same length as the input string.

Example 1

class Program{
   static void Main(string[] args){
      string myString = "wAr aNd pEaCe";
      TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
      Console.WriteLine("\"{0}\" to titlecase: {1}", myString, myTI.ToTitleCase(myString));
      Console.ReadLine();
   }
}

Output

"war and peace" to titlecase: War And Peace

Example 2

class Program{
   static void Main(string[] args){
      string[] values = {
         "a tale of three cities", "gROWL rescue",
         "inside the office", "sports and tennis",
         "The Return of Christmas Holmes"
      };
      TextInfo ti = CultureInfo.CurrentCulture.TextInfo;
      foreach (var value in values)
      Console.WriteLine("{0} −−> {1}", value, ti.ToTitleCase(value));
      Console.ReadLine();
   }
}

Output

a tale of three cities −−> A Tale Of Three Cities
gROWL rescue −−> Growl Rescue
inside the office −−> Inside The Office
sports and tennis −−> Sports And Tennis
The Return of Christmas Holmes −−> The Return Of Christmas Holmes
raja
Published on 05-Nov-2020 18:24:21
Advertisements