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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With