How to convert CamelCase to snake_case in C #?

4

I would like to know how to convert a string with CamelCase to snake_case into C #.

For example:

 EuAmoCsharp => eu_amo_csharp
 SnakeCase   => snake_case
    
asked by anonymous 04.07.2016 / 18:29

2 answers

6

It would look something like this:

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 #. Then I can use:

stringCamel.Select()

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

The conditional is simpler to understand:

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

I check if i is greater than zero and if the current character is uppercase, this is because I do not want to write _ before the first character.

If the character is uppercase, I type _ and the character in lower case. If not, just write the character.

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

    
04.07.2016 / 18:33
3

Just curious, you can do with regex too, but it's a bit slower.

string stringSnake = Regex.Replace(input, "(?<=.)([A-Z])", "_$0", RegexOptions.Compiled);
    
04.07.2016 / 18:40