How to capitalize the first letter of a string in C#

In C#, the Toupper() function of the char class converts a character into uppercase. In the case that we will be discussing, only the first character of the string needs to be converted to uppercase; the rest of the string will stay as it is.

svg viewer

The first character of the string can be indexed as str[0], where str is the original string. str.Substring(1) will return the remaining string, i.e., the whole str except the first character.

Code

The code snippet below illustrates the solution discussed above:

class CapitalizeFirstLetter
{
static void Main()
{
string str = "educative";
if (str.Length == 0)
System.Console.WriteLine("Empty String");
else if (str.Length == 1)
System.Console.WriteLine(char.ToUpper(str[0]));
else
System.Console.WriteLine(char.ToUpper(str[0]) + str.Substring(1));
}
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved