tags:

views:

232

answers:

2

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"
+7  A: 

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.

xsl
Thanks, I don't know why I didn't find it searching
Juan Manuel
This still assumes that the first letter is the right one to change. Not perfectly culture-safe yet.
Karl
first example will throw an exception if the string length is zero. Should add "if (string.IsNullOrEmpty(input)) return input;" at the top.
Michael Meadows
Thank you, added it to the post.
xsl
+8  A: 

System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase

It has the advantage of being culture-safe.

Chris
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
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