BestPractice - Transform first character of a string into lower case

前端 未结 11 2013

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

My approaches:

1.

public static string ReplaceFir         


        
相关标签:
11条回答
  • 2020-12-04 12:06

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

    0 讨论(0)
  • 2020-12-04 12:09

    Mine is

    if (!string.IsNullOrEmpty (val) && val.Length > 0)
    {
        return val[0].ToString().ToLowerInvariant() + val.Remove (0,1);   
    }
    
    0 讨论(0)
  • 2020-12-04 12:17

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-04 12:18

    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".

    0 讨论(0)
  • 2020-12-04 12:21

    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())
    
    0 讨论(0)
  • 2020-12-04 12:23

    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;
    
    0 讨论(0)
提交回复
热议问题