Convert String To camelCase from TitleCase C#

后端 未结 11 1522

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:52

    Here is my code, in case it is useful to anyone

        // This converts to camel case
        // Location_ID => LocationId, and testLEFTSide => TestLeftSide
    
        static string CamelCase(string s)
        {
            var x = s.Replace("_", "");
            if (x.Length == 0) return "Null";
            x = Regex.Replace(x, "([A-Z])([A-Z]+)($|[A-Z])",
                m => m.Groups[1].Value + m.Groups[2].Value.ToLower() + m.Groups[3].Value);
            return char.ToUpper(x[0]) + x.Substring(1);
        }
    

    The last line changes first char to uppercase, but you can change to lowercase, or whatever you like.

提交回复
热议问题