How to capitalize the first character of each word, or the first character of a whole string, with C#?

As discussed in the comments of @miguel’s answer, you can use TextInfo.ToTitleCase which has been available since .NET 1.1. Here is some code corresponding to your example:

string lipsum1 = "Lorem lipsum et";

// Creates a TextInfo based on the "en-US" culture.
TextInfo textInfo = new CultureInfo("en-US",false).TextInfo;

// Changes a string to titlecase.
Console.WriteLine("\"{0}\" to titlecase: {1}", 
                  lipsum1, 
                  textInfo.ToTitleCase( lipsum1 )); 

// Will output: "Lorem lipsum et" to titlecase: Lorem Lipsum Et

It will ignore casing things that are all caps such as “LOREM LIPSUM ET” because it is taking care of cases if acronyms are in text so that “IEEE” (Institute of Electrical and Electronics Engineers) won’t become “ieee” or “Ieee”.

However if you only want to capitalize the first character you can do the solution that is over here… or you could just split the string and capitalize the first one in the list:

string lipsum2 = "Lorem Lipsum Et";

string lipsum2lower = textInfo.ToLower(lipsum2);

string[] lipsum2split = lipsum2lower.Split(' ');

bool first = true;

foreach (string s in lipsum2split)
{
    if (first)
    {
        Console.Write("{0} ", textInfo.ToTitleCase(s));
        first = false;
    }
    else
    {
        Console.Write("{0} ", s);
    }
}

// Will output: Lorem lipsum et 

Leave a Comment