How to Lowercase the First Letter of a String in C#
Greetings, friends! Today, I will discuss a simple approach for transforming the first letter of a string to lowercase using C#. You may be wondering why I need to make a blog post about this. Can't we just use the String.ToLower()
method? If we run this method, it'll convert the entire string to lowercase:
using System;
public class Program
{
public static void Main()
{
string str = "PineapplePizza";
Console.WriteLine(str.ToLower());
// OUTPUT: pineapplepizza
}
}
You may find yourself in the situation where you're dealing with strings that are in Pascal case such as HelloWorld
or PineapplePizza
. However, you may want to convert these strings to Camel case instead. Common examples of strings that are in Camel case include iPhone
or eBay
. The following code snippet shows how to convert only the first letter of a string to lowercase.
using System;
public class Program
{
public static void Main()
{
string str = "PineapplePizza";
Console.WriteLine(char.ToLower(str[0]) + str.Substring(1));
// OUTPUT: pineapplePizza
}
}
You can try out this code by copying and pasting it to .NET Fiddle.
In the code above, we can grab the first letter of a string by using str[0]
. This will return a Char structure, which represents a single character. We can then use char.ToLower
to lowercase the first letter.
The String.Substring method retrieves part of a string, starting at a specified index. By passing in the value, 1, to this method, we are extracting the entire string except the first character.
Finally, we can use string concatenation to create the final string!