how to i capitalize only the first letter of a string in csharp

To capitalize only the first letter of a string in C#, you can use the string class's ToUpper and Substring methods as follows:

main.cs
string inputString = "hello world";
string resultString = inputString.Substring(0, 1).ToUpper() + inputString.Substring(1);
Console.WriteLine(resultString); // Output: "Hello world"
182 chars
4 lines

In the code above, we first declare a string variable named inputString and initialize it with the input string "hello world". Then, we declare another string variable named resultString, which will hold the capitalized string.

To capitalize the first letter of the input string, we use the Substring method to get the first character of the string (i.e., the character at index 0), and then call the ToUpper method on that character to convert it to its uppercase equivalent. We then concatenate the uppercase first letter with the rest of the input string (i.e., the substring starting at index 1), and assign the resulting string to the resultString variable.

Finally, we print out the resultString using the Console.WriteLine method, which will output the capitalized string "Hello world".

gistlibby LogSnag