We can capitalize the first letter of a string using several methods. Here are a few different ways to achieve this:
- Using ToUpper and Substring methods:
string input = "hello world";
string capitalized = input.Substring(0, 1).ToUpper() + input.Substring(1);
Console.WriteLine(capitalized); // Output: "Hello world"
- Using TextInfo from System.Globalization:
using System.Globalization;
string input = "hello world";
TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo;
string capitalized = textInfo.ToTitleCase(input);
Console.WriteLine(capitalized); // Output: "Hello World"
- Using StringBuilder (useful for larger strings where performance matters):
using System.Text;
string input = "hello world";
StringBuilder sb = new StringBuilder(input);
sb[0] = char.ToUpper(sb[0]);
string capitalized = sb.ToString();
Console.WriteLine(capitalized); // Output: "Hello world"
These methods will capitalize the first letter of the string without modifying the rest of the string. Choose the one that suits your needs best based on your specific use case.
Posted On:
31-Jul-2023 22:56