How to convert Camelcase to snake_case in C#?

Asked

Viewed 458 times

4

I would like to know how to convert a string with Camelcase for snake_case in C#.

For example:

 EuAmoCsharp => eu_amo_csharp
 SnakeCase   => snake_case
  • 3

    What code do you have so far?

  • I’m learning C# now. I have no idea how to do.

  • In the Github has shown the reverse.

2 answers

6


It would be something like that:

string stringSnake = string.Concat(
                         stringCamel.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString().ToLower() : x.ToString().ToLower())
                     ); 

I made you a Fiddle.

Explaining:

string is an enumeration of char in C#. So I can use:

stringCamel.Select()

One of the ways to use Select is specifying in the predicate two variables, being x the current iteration character and i the index of this iteration.

The parole is simpler to understand:

i > 0 && char.IsUpper(x) ? "_" + x.ToString().ToLower() : x.ToString().ToLower()

I confirm whether i is greater than zero and if the current character is capitalized, this is because I don’t want to write _ before the first character.

If the character is capitalized, I write _ and the character in lowercase. Otherwise, I just type the character.

I need to keep ToLower() in both results because of the first character.

  • Gypsy, IF I ask you to explain this code to me, would you? I know how to make Camelcase for snake_case in c#, but I would never do it this way. Explain it to me nicely?

  • @Paulohdsousa For sure.

  • 1

    Interesting answer. + 1

  • 1

    I had not understood i > 0, it was easy to understand after you explained, thank you very much. @Cigano Morrison Mendez

  • @Ciganomorrisonmendez very well explained. Although in this question I avoided the "code golf", but became very small the code.

3

Just out of curiosity, you can do with regex too, but it’s a little slower

string stringSnake = Regex.Replace(input, "(?<=.)([A-Z])", "_$0", RegexOptions.Compiled);
  • Just remembering that this is a little slower, but works well.

  • 1

    Incidentally, much slower.

  • Why is it slower? Regex is slower in general?

  • Why is it slower? @jbueno

  • I can’t answer you for sure @Paulohdsousa, but generally working with regex is more expensive. In this particular case I tested my solution and that of the Gypsy, so I know it is slower...

  • I asked a question http://answall.com/questions/138705/fazer-replaces%C3%A7%C3%A3o-de-strings-with-regex-%C3%A9-slower-than-replace

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.