简体   繁体   中英

BestPractice - Transform first character of a string into lower case

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?

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.

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.

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);
    }
}

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;
}

Mine is

if (!string.IsNullOrEmpty (val) && val.Length > 0)
{
    return val[0].ToString().ToLowerInvariant() + val.Remove (0,1);   
}

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. Eg you would not want "AIDS" to become "aIDS".

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.

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

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

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;

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);
        }
    }
}

用这个:

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

如果您知道格式不是更改数据,并且只需要连接,那么使用String.Concat比使用String.Format更好。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM