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"
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"
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.
System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase
It has the advantage of being culture-safe.