11

Is there a method to do that? Could it be done with an extension method?

I want to achieve this:

string s = "foo".CapitalizeFirstLetter();
// s is now "Foo"
juan
  • 80,295
  • 52
  • 162
  • 195

4 Answers4

19

A simple extension method, that will capitalize the first letter of a string. As Karl pointed out, this assumes that the first letter is the right one to change and is therefore not perfectly culture-safe.

public static string CapitalizeFirstLetter(this String input)
{
    if (string.IsNullOrEmpty(input)) 
        return input;

    return input.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture) +
        input.Substring(1, input.Length - 1);
}

You can also use System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase. The function will convert the first character of each word to upper case. So if your input string is have fun the result will be Have Fun.

public static string CapitalizeFirstLetter(this String input)
{
     if (string.IsNullOrEmpty(input)) 
         return input;

     return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input);
}

See this question for more information.

Community
  • 1
  • 1
xsl
  • 17,116
  • 18
  • 71
  • 112
10

System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase

It has the advantage of being culture-safe.

Chris
  • 27,596
  • 25
  • 124
  • 225
  • After reading the remarks in the MSDN docs, it turns out this method just changes first letters to uppercase regardless of any real cultural details anyway. +1 for pointing out obscure framework method, -1 for the specified method being misleading/broken. – ScottS Apr 14 '09 at 16:52
  • 1
    Well the optimist would say that if you use it now, it may actually function as expected in the future. At any rate, it does exactly what was requested, and is built into the framework :P – Chris Apr 14 '09 at 17:29
0

Try this:

static public string UpperCaseFirstCharacter(this string text) {
    return Regex.Replace(text, "^[a-z]", m => m.Value.ToUpper());
}
JoelFan
  • 37,465
  • 35
  • 132
  • 205
0

In my case the text input can also be all in capitals.

I added a ToLower before the ToTitleCase is done:

    public static string CapitalizeFirstLetter(this string input)
    {
        if (string.IsNullOrWhiteSpace(input))
        {
            return input;
        }

        return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input.ToLower(CultureInfo.CurrentCulture));
    }
Patrick Koorevaar
  • 1,219
  • 15
  • 24