BestPractice - Transform first character of a string into lower case

Viewed 65059

I'd like to have a method that transforms the first character of a string into lower case.

My approaches:

1.

public static string ReplaceFirstCharacterToLowerVariant(string name)
{
    return String.Format("{0}{1}", name.First().ToString().ToLowerInvariant(), name.Substring(1));
}

2.

public static IEnumerable<char> FirstLetterToLowerCase(string value)
{
    var firstChar = (byte)value.First();
    return string.Format("{0}{1}", (char)(firstChar + 32), value.Substring(1));
}

What would be your approach?

13 Answers

The fastest solution I know without abusing c#:

public static string LowerCaseFirstLetter(string value)
{
    if (value?.Length > 0)
    {
        var letters = value.ToCharArray();
        letters[0] = char.ToLowerInvariant(letters[0]);
        return new string(letters);
    }
    return value;
}

If you care about performance I would go with

  public static string FirstCharToLower(this string str)
    => string.Create(str.Length, str, (output, input) =>
      {
        input.CopyTo(output);
        output[0] = char.ToLowerInvariant(input[0]);
      });

I did some quick benchmarking and it seems to be at least twice as fast as the fastest solution posted here and 3.5 times faster than the worst one across multiple input lengths.

There is no input checking as it should be the responsibility of the caller. Allowing you to prepare your data in advance and do fast bulk processing not being slowed down by having branches in your hot path if you ever need it.

This is a little extension method using latest syntax and correct validations

public static class StringExtensions
{
    public static string FirstCharToLower(this string input)
    {
        switch (input)
        {
            case null: throw new ArgumentNullException(nameof(input));
            case "": throw new ArgumentException($"{nameof(input)} cannot be empty", nameof(input));
            default: return input.First().ToString().ToLower() + input.Substring(1);
        }
    }
}

Use This:

string newName= name[0].ToString().ToLower() + name.Substring(1);

If you don't want to reference your string twice in your expression you could do this using System.Linq.

new string("Hello World".Select((c, i) => i == 0 ? char.ToLower(c) : c).ToArray())

That way if your string comes from a function, you don't have to store the result of that function.

new string(Console.ReadLine().Select((c, i) => i == 0 ? char.ToLower(c) : c).ToArray())

With range operator C# 8.0 or above you can do this:

Char.ToLowerInvariant(name[0]) + name[1..];
Related