115

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.

1
  • 3
    You should just post your own answer instead of putting a solution in the question, its a little more confusing this way. Commented Feb 22, 2019 at 19:08

20 Answers 20

140

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)
8
  • 10
    That doesn't work with acronyms in the beginning (e.g., VATReturnAmount). See my answer.
    – Mojtaba
    Commented Nov 14, 2019 at 9:42
  • 2
    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. Commented Jun 24, 2020 at 2:20
  • 3
    In .NET Core C#9 you can make it even more concise: return char.ToLowerInvariant(s[0]) + s[1..];
    – Matthew M.
    Commented Mar 23, 2022 at 12:49
  • 1
    With time, this answer should get more and more downvoted, and the other answer (System.Text.Json.JSonNamingPolicy.CamelCase) should be more and more upvoted. Commented Apr 12, 2023 at 9:07
  • 1
    @jeancallisti - Actually my answer should be removed but you cannot delete the accepted answer. There needs to be a way to flag something as obsolete or link it to a specific framework. In the meantime I will update my answer to point people below.
    – Bronumski
    Commented Apr 12, 2023 at 14:36
102

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.

3
  • 3
    this did not work for me, it converted everything to lower case in my situation
    – AussieJoe
    Commented Mar 16, 2021 at 16:57
  • 3
    Just to note, this does not remove spaces so you need to do JsonNamingPolicy.CamelCase.ConvertName(str).Replace(" ", string.Empty)
    – Dave
    Commented Feb 17, 2022 at 10:05
  • 1
    @AussieJoe if the input string (which you didn't provide) was all capital letters then the output string is expected to be all small letters because that's how the standard camel case handles acronyms Commented Apr 12, 2023 at 9:09
44

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();
2
  • 10
    The only issue I see is if the string is just a "A". It should return "a", right?
    – Diogo Luis
    Commented Aug 29, 2018 at 9:02
  • 1
    Does not handle the sneaky way camel case handles acronyms. I'd suggest using the native function provided by C#. Commented Apr 12, 2023 at 9:08
20

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);
    }
8
  • 4
    Finally an example that converts MYCase to myCase, instead of mYCase. Thanks! Commented Nov 7, 2018 at 20:31
  • @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
    Commented Nov 26, 2019 at 14:53
  • @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. Commented Dec 11, 2019 at 22:20
  • This converts to PascalCase not camelCase Commented Jun 24, 2020 at 3:20
  • @CraigShearer yes.... the last line can be ToLower if you want camelCase. Commented Jul 7, 2020 at 21:12
13

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;
            });
7
  • 1
    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
    – NibblyPig
    Commented Oct 12, 2020 at 17:51
  • 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.
    – HappyNomad
    Commented Jan 22, 2021 at 16:19
  • @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.
    – Mojtaba
    Commented Jan 27, 2021 at 9:20
  • Extending this one a bit. The above RegEx fails to match e.g. ABC123 (output is abC123). Capturing numbers in the last group using ([A-Z])([A-Z]+|[a-z0-9_]+)($|[A-Z0-9]\w*) will correctly output abc123 (while still working with ABCFoo et al). Commented Feb 16, 2023 at 13:32
  • This would be my second go-to answer after the native .Net method. any method that does not handle acronyms cannot be marked as the right answer. Commented Apr 12, 2023 at 9:10
7

Example 01

    public static string ToCamelCase(this string text)
    {
        return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text);
    }

Example 02

public static string ToCamelCase(this string text)
    {
        return string.Join(" ", text
                            .Split()
                            .Select(i => char.ToUpper(i[0]) + i.Substring(1)));
    }

Example 03

    public static string ToCamelCase(this string text)
    {
        char[] a = text.ToLower().ToCharArray();

        for (int i = 0; i < a.Count(); i++)
        {
            a[i] = i == 0 || a[i - 1] == ' ' ? char.ToUpper(a[i]) : a[i];

        }
        return new string(a);
    }
6
  • 5
    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!
    – Rick M.
    Commented Aug 16, 2018 at 15:00
  • 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).
    – s1cart3r
    Commented Mar 5, 2019 at 8:34
  • 3
    That was harsh? Commented Jun 6, 2019 at 11:28
  • @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.
    – ygoe
    Commented Nov 26, 2019 at 14:56
  • 2
    Most of all it doesn't even answer the question. It converts to TitleCase, which was not the question asked. Commented Feb 9, 2021 at 8:00
4

In .Net 6 and above

public static class CamelCaseExtension
{
  public static string ToCamelCase(this string str) => 
     char.ToLowerInvariant(str[0]) + str[1..];
}
3
  • Does not handle camel case acronyms. Cannot be considered correct. Commented Apr 12, 2023 at 9:11
  • What is a camel case acronym? Commented Apr 12, 2023 at 18:32
  • By "camel case acronym" I meant "the way camel case handles any kind of acronyms". Check the norm (or other answers) to see how camel case handles a sequence of capital letters. Commented Apr 13, 2023 at 8:55
4

If you are Ok with the Newtonsoft.JSON dependency, the following string extension method will help. The advantage of this approach is the serialization will work on par with standard WebAPI model binding serialization with high accuracy.

using System;
using Newtonsoft.Json.Serialization;

    public static class StringExtensions
    {
        private class CamelCasingHelper : CamelCaseNamingStrategy
        {
            private CamelCasingHelper(){}
            private static CamelCasingHelper helper =new CamelCasingHelper();
            public static string ToCamelCase(string stringToBeConverted)
            {
                return helper.ResolvePropertyName(stringToBeConverted);     
            }
            
        }
        public static string ToCamelCase(this string str)
        {
            return CamelCasingHelper.ToCamelCase(str);
        }
    }

Here is the working fiddle https://dotnetfiddle.net/pug8pP

2
  • 1
    Consider editing your answer to include the "using" statements at the top. Commented Apr 12, 2023 at 9:13
  • 1
    Added using statements Commented Apr 13, 2023 at 13:11
3

Adapted from Leonardo's answer:

static string PascalCase(string str) {
  TextInfo cultInfo = new CultureInfo("en-US", false).TextInfo;
  str = Regex.Replace(str, "([A-Z]+)", " $1");
  str = cultInfo.ToTitleCase(str);
  str = str.Replace(" ", "");
  return str;
}

Converts to PascalCase by first adding a space before any group of capitals, and then converting to title case before removing all the spaces.

1
public static string CamelCase(this string str)  
    {  
      TextInfo cultInfo = new CultureInfo("en-US", false).TextInfo;
      str = cultInfo.ToTitleCase(str);
      str = str.Replace(" ", "");
      return str;
    }

This should work using System.Globalization

1
  • This is good, but unfortunately it will convert PascalCase into Pascalcase. Commented Jun 27, 2019 at 13:23
1

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();
2
  • 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. Commented Jun 18, 2020 at 20:06
  • Wanted to upvote because it DOES handle camel case acronyms, but ended up downvoting because this answer is way too resource-consuming. Commented Apr 12, 2023 at 9:12
1
var camelCaseFormatter = new JsonSerializerSettings();
camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();

JsonConvert.SerializeObject(object, camelCaseFormatter));
2
  • While this might answer the question, it would be much more helpful if you explain your code a bit. Commented Apr 18, 2020 at 13:57
  • 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
    – Sras
    Commented Apr 8, 2021 at 1:32
1

Strings are immutable, but we can use unsafe code to make it mutable though. The string.Copy insured that the original string stays as is.

In order for these codes to run you have to allow unsafe code in your project.

        public static unsafe string ToCamelCase(this string value)
        {
            if (value == null || value.Length == 0)
            {
                return value;
            }

            string result = string.Copy(value);

            fixed (char* chr = result)
            {
                char valueChar = *chr;
                *chr = char.ToLowerInvariant(valueChar);
            }

            return result;
        }

This version modifies the original string, instead of returning a modified copy. This will be annoying though and totally uncommon. So make sure the XML comments are warning users about that.

        public static unsafe void ToCamelCase(this string value)
        {
            if (value == null || value.Length == 0)
            {
                return value;
            }

            fixed (char* chr = value)
            {
                char valueChar = *chr;
                *chr = char.ToLowerInvariant(valueChar);
            }

            return value;
        }

Why use unsafe code though? Short answer... It's super fast.

1

Here's my code which is pretty simple. My major objective was to ensure that camel-casing was compatible with what ASP.NET serializes objects to, which the above examples don't guarantee.

public static class StringExtensions
{
    public static string ToCamelCase(this string name)
    {
        var sb = new StringBuilder();
        var i = 0;
        // While we encounter upper case characters (except for the last), convert to lowercase.
        while (i < name.Length - 1 && char.IsUpper(name[i + 1]))
        {
            sb.Append(char.ToLowerInvariant(name[i]));
            i++;
        }

        // Copy the rest of the characters as is, except if we're still on the first character - which is always lowercase.
        while (i < name.Length)
        {
            sb.Append(i == 0 ? char.ToLowerInvariant(name[i]) : name[i]);
            i++;
        }

        return sb.ToString();
    }
}
0
    /// <summary>
    /// Gets the camel case from snake case.
    /// </summary>
    /// <param name="snakeCase">The snake case.</param>
    /// <returns></returns>
    private string GetCamelCaseFromSnakeCase(string snakeCase)
    {
        string camelCase = string.Empty;

        if(!string.IsNullOrEmpty(snakeCase))
        {
            string[] words = snakeCase.Split('_');
            foreach (var word in words)
            {
                camelCase = string.Concat(camelCase, Char.ToUpperInvariant(word[0]) + word.Substring(1));
            }

            // making first character small case
            camelCase = Char.ToLowerInvariant(camelCase[0]) + camelCase.Substring(1);
        }

        return camelCase;
    }
1
  • Please, add some description or comments for help them. Commented Aug 11, 2021 at 13:37
0

I use This method to convert the string with separated by "_" to Camel Case

public static string ToCamelCase(string? s)
        {
            var nameArr = s?.ToLower().Split("_");
            var str = "";
            foreach (var name in nameArr.Select((value, i) => new { value, i }))
            {
                if(name.i >= 1)
                {
                    str += string.Concat(name.value[0].ToString().ToUpper(), name.value.AsSpan(1));
                }
                else
                {
                    str += name.value ;
                }
            }
            return str;
        }

u can change the separated by "_" with any other you want.

0
public static class StringExtension
{
    public static string ToCamelCase(this string str)
    {
        return string.Join(" ", str
                     .Split()
                     .Select(i => char.ToUpper(i[0]) + i.Substring(1).ToLower()));
    }
}
0

When you cannot use System.Text.Json, for example in C# source generators that must target .netstandard2.0 and likely run in .NET Framework or something, here's my solution that can handle acronyms at the beginning. It also handles Unicode names properly. These are allowed as identifiers in C#, so why not convert them properly as well.

The regex distinguishes between upper-case letters and anything else only. The algorithm is as follows:

  • Empty string → empty string
  • Single character → ToLower that
  • Anything from the first lower-case letter on (actually, non-upper-case-letter) remains unchanged
  • The upper-case letter immediately before that is converted to lower case, except:
  • If there are more upper-case letters before that, only they are all converted to lower case

Maybe a bit complex to put in words, so here's the code finally:

static string PascalToCamelCase(string name) =>
    name.Length < 2 ?
        name.ToLowerInvariant() :
        Regex.Replace(
            name,
            @"^(\p{Lu}*)(\p{Lu})(\P{Lu}.*)$",
            m => m.Groups[1].Length > 0 ?
                m.Groups[1].Value.ToLowerInvariant() + m.Groups[2].Value + m.Groups[3].Value :
                m.Groups[2].Value.ToLowerInvariant() + m.Groups[3].Value);

The regex pattern \p{Lu} matches any upper-case letter. \P{Lu} matches everything else. (Reference)

-1

I had the same issue with titleCase so I just created one, hope this helps this is an extension method.

    public static string ToCamelCase(this string text)
    {
        if (string.IsNullOrEmpty(text))
            return text;

        var separators = new[] { '_', ' ' };
        var arr = text
            .Split(separators)
            .Where(word => !string.IsNullOrWhiteSpace(word));

        var camelCaseArr = arr
            .Select((word, i) =>
            {
                if (i == 0)
                    return word.ToLower();

                var characterArr = word.ToCharArray()
                    .Select((character, characterIndex) => characterIndex == 0
                        ? character.ToString().ToUpper()
                        : character.ToString().ToLower());

                return string.Join("", characterArr);
            });

        return string.Join("", camelCaseArr);
    }
-2

Simple and easy in build c#

using System;
using System.Globalization;

public class SamplesTextInfo  {

   public static void Main()  {

      // Defines the string with mixed casing.
      string myString = "wAr aNd pEaCe";

      // Creates a TextInfo based on the "en-US" culture.
      TextInfo myTI = new CultureInfo("en-US",false).TextInfo;

      // Changes a string to lowercase.
      Console.WriteLine( "\"{0}\" to lowercase: {1}", myString, myTI.ToLower( myString ) );

      // Changes a string to uppercase.
      Console.WriteLine( "\"{0}\" to uppercase: {1}", myString, myTI.ToUpper( myString ) );

      // Changes a string to titlecase.
      Console.WriteLine( "\"{0}\" to titlecase: {1}", myString, myTI.ToTitleCase( myString ) );
   }
}

/*
This code produces the following output.

"wAr aNd pEaCe" to lowercase: war and peace
"wAr aNd pEaCe" to uppercase: WAR AND PEACE
"wAr aNd pEaCe" to titlecase: War And Peace

*/
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.