Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a CapitalizeFirstLetter method?

Tags:

string

c#

.net

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"
like image 835
juan Avatar asked Apr 14 '09 16:04

juan


1 Answers

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.

like image 179
xsl Avatar answered Oct 22 '22 16:10

xsl