Search code examples
c#camelcasingtolowertitle-case

Convert String To camelCase from TitleCase C#


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 character in the string to lower case and for some reason, I can not figure out how to accomplish it.

class Program
{
    static void Main(string[] args)
    {
        string functionName = "zebulans_nightmare";
        TextInfo txtInfo = new CultureInfo("en-us", false).TextInfo;
        functionName = txtInfo.ToTitleCase(functionName).Replace('_', ' ').Replace(" ", String.Empty);
        Console.Out.WriteLine(functionName);
        Console.ReadLine();
    }
}

Results: ZebulansNightmare

Desired Results: zebulansNightmare

UPDATE:

class Program
{
    static void Main(string[] args)
    {
        string functionName = "zebulans_nightmare";
        TextInfo txtInfo = new CultureInfo("en-us", false).TextInfo;
        functionName = txtInfo.ToTitleCase(functionName).Replace("_", string.Empty).Replace(" ", string.Empty);
        functionName = $"{functionName.First().ToString().ToLowerInvariant()}{functionName.Substring(1)}";
        Console.Out.WriteLine(functionName);
        Console.ReadLine();
    }
}

Produces the desired output.


Solution

  • Note: My answer is outdated, see this answer below which uses System.Text.Json which is available out of the box with dotnet core or via nuget for older dotnet framework applications

    Original answer:

    You just need to lower the first char in the array. See this answer

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

    As a side note, seeing as you are removing spaces you can replace the underscore with an empty string.

    .Replace("_", string.Empty)