Convert String To camelCase from TitleCase C#

后端 未结 11 1638

I have a string that I converted to a TextInfo.ToTitleCase and removed the underscores and joined the string together. Now I need to change the first and only the first charact

11条回答
  •  無奈伤痛
    2021-02-04 23:40

    Here's my code, includes lowering all upper prefixes:

    public static class StringExtensions
    {
        public static string ToCamelCase(this string str)
        {
            bool hasValue = !string.IsNullOrEmpty(str);
    
            // doesn't have a value or already a camelCased word
            if (!hasValue || (hasValue && Char.IsLower(str[0])))
            {
                return str;
            }
    
            string finalStr = "";
    
            int len = str.Length;
            int idx = 0;
    
            char nextChar = str[idx];
    
            while (Char.IsUpper(nextChar))
            {
                finalStr += char.ToLowerInvariant(nextChar);
    
                if (len - 1 == idx)
                {
                    // end of string
                    break;
                }
    
                nextChar = str[++idx];
            }
    
            // if not end of string 
            if (idx != len - 1)
            {
                finalStr += str.Substring(idx);
            }
    
            return finalStr;
        }
    }
    

    Use it like this:

    string camelCasedDob = "DOB".ToCamelCase();
    

提交回复
热议问题