Is there a CapitalizeFirstLetter method?

Is there any way to do this? Can this be done using the extension method?

I want to achieve this:

string s = "foo".CapitalizeFirstLetter();
// s is now "Foo"
+5
source share
3 answers

A simple extension method that will use the first letter of a string. As Karl noted, this suggests that the first letter is correct for change and therefore not entirely safe for culture.

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 converts the first character of each word to uppercase. Therefore, if your input line 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);
}

. .

+15

:

static public string UpperCaseFirstCharacter(this string text) {
    return Regex.Replace(text, "^[a-z]", m => m.Value.ToUpper());
}
0
source

All Articles