Convert String To camelCase from TitleCase C#

130,963

Solution 1

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)

Solution 2

Implemented Bronumski's answer in an extension method (without replacing underscores).

 public static class StringExtension
 {
     public static string ToCamelCase(this string str)
     {                    
         if(!string.IsNullOrEmpty(str) && str.Length > 1)
         {
             return char.ToLowerInvariant(str[0]) + str.Substring(1);
         }
         return str.ToLowerInvariant();
     }
 }
 //Or
 public static class StringExtension
 {
     public static string ToCamelCase(this string str) =>
         string.IsNullOrEmpty(str) || str.Length < 2
         ? str.ToLowerInvariant()
         : char.ToLowerInvariant(str[0]) + str.Substring(1);
 }

and to use it:

string input = "ZebulansNightmare";
string output = input.ToCamelCase();

Solution 3

If you're using .NET Core 3 or .NET 5, you can call:

System.Text.Json.JsonNamingPolicy.CamelCase.ConvertName(someString)

Then you'll definitely get the same results as ASP.NET's own JSON serializer.

Solution 4

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.ToLower(x[0]) + x.Substring(1);
    }

If you prefer Pascal-case use:

    static string PascalCase(string s)
    {
        var x = CamelCase(s);
        return char.ToUpper(x[0]) + x.Substring(1);
    }

Solution 5

The following code works with acronyms as well. If it is the first word it converts the acronym to lower case (e.g., VATReturn to vatReturn), and otherwise leaves it as it is (e.g., ExcludedVAT to excludedVAT).

name = Regex.Replace(name, @"([A-Z])([A-Z]+|[a-z0-9_]+)($|[A-Z]\w*)",
            m =>
            {
                return m.Groups[1].Value.ToLower() + m.Groups[2].Value.ToLower() + m.Groups[3].Value;
            });
Share:
130,963

Related videos on Youtube

Gabriel_W
Author by

Gabriel_W

Currently, a Student looking to sharpen my skills and learn as much as I can.

Updated on July 08, 2022

Comments

  • Gabriel_W
    Gabriel_W 11 months

    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. Thanks in advance for the help.

    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

    • StayOnTarget
      StayOnTarget over 4 years
      You should just post your own answer instead of putting a solution in the question, its a little more confusing this way.
  • Gabriel_W
    Gabriel_W over 6 years
    Thanks just what I needed.
  • Gabriel_W
    Gabriel_W over 6 years
    Good call. Made the adjustments and updated the question.
  • Rick M.
    Rick M. almost 5 years
    Welcome to StackOverflow! Although this might answer the question, consider adding text to why this is a suitable answer and links to support your answer!
  • Diogo Luis
    Diogo Luis almost 5 years
    The only issue I see is if the string is just a "A". It should return "a", right?
  • Muster Station
    Muster Station over 4 years
    Finally an example that converts MYCase to myCase, instead of mYCase. Thanks!
  • s1cart3r
    s1cart3r over 4 years
    Given that no other answer has an essay supporting the answer and only one has a link I think this a bit harsh, or very "StackOverflow-ish". The first answer Kenny gave was a good anser imo (although I agree there is a typo in te to text).
  • CodeWarrior
    CodeWarrior about 4 years
    That was harsh?
  • Rhys van der Waerden
    Rhys van der Waerden almost 4 years
    This is good, but unfortunately it will convert PascalCase into Pascalcase.
  • Mojtaba
    Mojtaba over 3 years
    That doesn't work with acronyms in the beginning (e.g., VATReturnAmount). See my answer.
  • ygoe
    ygoe over 3 years
    @MusterStation But why? Shouldn't you just have "MyCase" in the first place? If "Y" is uppercase, then it's probably another word, right?
  • ygoe
    ygoe over 3 years
    @CodeWarrior No, it wasn't. He could have said "please" though. BTW, the code style looks ugly (probably not just to me), hard to read.
  • John Henckel
    John Henckel over 3 years
    @ygoe maybe. in "MYCase" perhaps M is a word, Y is a word, and Case is a word. However, it is more likely that "MY" is a two letter acronym. For example "innerHTML" is two words, not five.
  • Klaus Gütter
    Klaus Gütter about 3 years
    While this might answer the question, it would be much more helpful if you explain your code a bit.
  • Legacy Code
    Legacy Code almost 3 years
    Sorry but this is not a good code at all... Concatenating strings create new strings... In this case you are creating as many strings as your original string in str. If you have a long string, the GC will hate you.
  • Tushee
    Tushee almost 3 years
    Agreed with @Mojtaba. DON'T use this if you want to have compatibility with camelCase JSON serialization in ASP.NET. Acronyms at the beginning won't come out the same.
  • Tushee
    Tushee almost 3 years
    This converts to PascalCase not camelCase
  • John Henckel
    John Henckel almost 3 years
    @CraigShearer yes.... the last line can be ToLower if you want camelCase.
  • NibblyPig
    NibblyPig over 2 years
    Thank you, this is much better. It matches the behaviour of MVC when you return Json(new { CAPSItem = ... } whereas the accepted answer will create a mismatch
  • HappyNomad
    HappyNomad over 2 years
    A problem with acronyms arises if you must convert from camelCase back to PascalCase. For example, I don't see how to convert vatReturn back to VATReturn. Better to use VatReturn as your pascal naming convention, then you can stick to just modifying the first letter.
  • Mojtaba
    Mojtaba over 2 years
    @HappyNomad although your point is valid in its context, the question is about converting to camelCase; that means using VatReturn instead of vatReturn for acronyms is not an answer for this question.
  • Joep Beusenberg
    Joep Beusenberg over 2 years
    Why is your function called CamelCase while it actually converts to PascalCase? :)
  • Joep Beusenberg
    Joep Beusenberg over 2 years
    Most of all it doesn't even answer the question. It converts to TitleCase, which was not the question asked.
  • John Henckel
    John Henckel over 2 years
    @JoepBeusenberg ok i fixed it
  • AussieJoe
    AussieJoe about 2 years
    this did not work for me, it converted everything to lower case in my situation
  • Sras
    Sras about 2 years
    this is quite strange forward answer. you just create JsonSerilizerSetting by setting its contractresovler option to Camelcase. So, the object, is anything you want to serilize, together wtih the setting. you can customize any setting you wish to
  • Filipe Piletti Plucenio almost 2 years
    Please, add some description or comments for help them.
  • Dave
    Dave over 1 year
    Just to note, this does not remove spaces so you need to do JsonNamingPolicy.CamelCase.ConvertName(str).Replace(" ", string.Empty)
  • Matthew M.
    Matthew M. about 1 year
    In .NET Core C#9 you can make it even more concise: return char.ToLowerInvariant(s[0]) + s[1..];
  • Cameron MacFarland
    Cameron MacFarland about 1 year
    To fix the "InnerHTMLExample" change the regex to "(^[A-Z])([A-Z]+)($|[A-Z])"