154

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?

onof
  • 17,167
  • 7
  • 49
  • 85
Rookian
  • 19,841
  • 28
  • 110
  • 180

13 Answers13

259

I would use simple concatenation:

Char.ToLowerInvariant(name[0]) + name.Substring(1)

The first solution is not optimized because string.Format is slow and you don't need it if you have a format that will never change. It also generates an extra string to covert the letter to lowercase, which is not needed.

The approach with "+ 32" is ugly / not maintainable as it requires knowledge of ASCII character value offsets. It will also generate incorrect output with Unicode data and ASCII symbol characters.

user2864740
  • 60,010
  • 15
  • 145
  • 220
onof
  • 17,167
  • 7
  • 49
  • 85
  • 4
    i would do it: `char.ToLower(name[0]).ToString() + name.Substring(1)` – Andrey Aug 25 '10 at 10:50
  • I thought that concatination of strings with the + operator is slow and ugly, isn't it? – Rookian Aug 25 '10 at 11:02
  • Actually, getting rid of that conversion makes it use a slightly slower version of `String.Concat` :) – Thorarin Aug 25 '10 at 11:03
  • 8
    @Rookian: the `+` operator is slow when you are concatenating lots of strings. In that case a `StringBuilder` would perform much better. However, `+` is much faster than `string.Format`. Use the latter when you actually need to format something (like displaying integers, doubles or dates). – Dirk Vollmar Aug 25 '10 at 11:09
  • 6
    @0x03: it's only slow if you're concatenating lots of strings iteratively. If you concatenate them all in a single operation, the `+` operator is not slow at all, because the compiler turns it into a `String.Concat` (however `String.Join` is faster than `String.Concat` for some silly reason). – Thorarin Aug 25 '10 at 13:39
  • 2
    A faster method is this: public static string ToFirstLetterLower(string text) { var charArray = text.ToCharArray(); charArray[0] = char.ToLower(charArray[0]); return new string(charArray); } – Matteo Migliore Aug 12 '14 at 10:02
  • 3
    I used extension `public static string ToLowerFirst(this string source) { if (string.IsNullOrWhiteSpace(source)) return source; var charArray = source.ToCharArray(); charArray[0] = char.ToLower(charArray[0]); return new string(charArray); }` Based on @MatteoMigliore's comment. – KregHEk Dec 21 '15 at 08:36
  • 2
    Unless you are concatenating strings in a loop, worrying about the difference between +, stringbuilder, string.format, or string.concat is premature optimization. – stannius Oct 17 '16 at 17:26
72

Depending on the situation, a little defensive programming might be desirable:

public static string FirstCharacterToLower(string str)
{
    if (String.IsNullOrEmpty(str) || Char.IsLower(str, 0))
        return str;

    return Char.ToLowerInvariant(str[0]) + str.Substring(1);
}

The if statement also prevents a new string from being built if it's not going to be changed anyway. You might want to have the method fail on null input instead, and throw an ArgumentNullException.

As people have mentioned, using String.Format for this is overkill.

dav_i
  • 27,509
  • 17
  • 104
  • 136
Thorarin
  • 47,289
  • 11
  • 75
  • 111
  • Correct me if I'm wrong but str.Substring(1) will return the symbol at position 1 as the count for this method is not indicated. so you will have char[0] in lower case + the char at position 1 So I preferred to remove one char starting from first char in the string. The result is the string without first letter. Then i will add this string to first char that is converted to lower case – fedotoves Aug 25 '10 at 11:34
  • 4
    @B-Rain: consider yourself corrected: http://msdn.microsoft.com/en-us/library/hxthx5h6%28VS.90%29.aspx – Thorarin Aug 25 '10 at 13:37
9

Just in case it helps anybody who happens to stumble across this answer.

I think this would be best as an extension method, then you can call it with yourString.FirstCharacterToLower();

public static class StringExtensions
{
    public static string FirstCharacterToLower(this string str)
    {
        if (String.IsNullOrEmpty(str) || Char.IsLower(str, 0))
        {
            return str;
        }

        return Char.ToLowerInvariant(str[0]) + str.Substring(1);
    }
}
carlcheel
  • 621
  • 6
  • 11
5

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;
}
Rjz
  • 61
  • 1
  • 2
3

Mine is

if (!string.IsNullOrEmpty (val) && val.Length > 0)
{
    return val[0].ToString().ToLowerInvariant() + val.Remove (0,1);   
}
David Clarke
  • 12,888
  • 9
  • 86
  • 116
fedotoves
  • 757
  • 6
  • 7
  • 4
    I'm curious, why the `val.Remove`? Seems a little counter-intuitive to me. – Thorarin Aug 25 '10 at 11:04
  • @Thorarin obviously because you want to remove the first char (because you are adding the lower case version in front) – Riki Jun 16 '17 at 06:37
2

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.

Hnus
  • 912
  • 2
  • 9
  • 24
2

I like the accepted answer, but beside checking string.IsNullOrEmpty I would also check if Char.IsLower(name[1]) in case you are dealing with abbreviation. E.g. you would not want "AIDS" to become "aIDS".

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
1

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

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

Combined a few and made it a chainable extension. Added short-circuit on whitespace and non-letter.

public static string FirstLower(this string input) => 
    (!string.IsNullOrWhiteSpace(input) && input.Length > 0 
        && char.IsLetter(input[0]) && !char.IsLower(input[0]))
    ? input[0].ToString().ToLowerInvariant() + input.Remove(0, 1) : input;
Randy Buchholz
  • 233
  • 3
  • 8
0

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);
        }
    }
}
Carlos Muñoz
  • 17,397
  • 7
  • 55
  • 80
  • 1
    Not sure if throwing an exception would be the best solution. Is the string is null or empty, just return the null or empty string. – R. de Veen Sep 28 '18 at 08:56
  • If String is null or empty the operation doesn't make sense as there is no first char to change to lowercase. – Carlos Muñoz Sep 28 '18 at 09:18
0

Use This:

string newName= name[0].ToString().ToLower() + name.Substring(1);
yaakov
  • 5,552
  • 35
  • 48
hojjat.mi
  • 1,414
  • 16
  • 22
0

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())
-3

It is better to use String.Concat than String.Format if you know that format is not change data, and just concatenation is desired.

Pavel Kovalev
  • 7,521
  • 5
  • 45
  • 67
Konstantin Isaev
  • 642
  • 8
  • 14