How to separate "words" in Camelcase in C#?

Asked

Viewed 453 times

13

How can I separate "words" into Camelcase using hyphen for example?

String:

string example = "CamelCase";
// CamelCase para:
// Camel-Case

and enumerator:

enum Example {
    CamelCase
}

Example.CamelCase.ToString();
// CamelCase para:
// Camel-Case

5 answers

16


Option more performative, flexible, integrated and more correct according to the criterion that one already has a separator should not put another:

using static System.Console;
using System.Text;

public static class Program {
    public static void Main() {
        WriteLine("CamelCase".SplitCamelCase());
        WriteLine("Camel-Case".SplitCamelCase());
        WriteLine("Camel---Case".SplitCamelCase());
        WriteLine("Camel.Case".SplitCamelCase());
        WriteLine("Ca".SplitCamelCase());
        WriteLine("aC".SplitCamelCase());
        WriteLine("CC".SplitCamelCase());
        WriteLine("C".SplitCamelCase());
        WriteLine("CamelCaseC".SplitCamelCase());
        WriteLine("".SplitCamelCase());
        WriteLine("pascalCase".SplitCamelCase());
        WriteLine("CamelCase".SplitCamelCase('-', ""));
        WriteLine("Camel-Case".SplitCamelCase('-', ""));
        WriteLine("Camel---Case".SplitCamelCase('-', ""));
        WriteLine("Camel.Case".SplitCamelCase('-', ""));
        WriteLine("Ca".SplitCamelCase('-', ""));
        WriteLine("aC".SplitCamelCase('-', ""));
        WriteLine("CC".SplitCamelCase('-', ""));
        WriteLine("C".SplitCamelCase('-', ""));
        WriteLine("CamelCaseC".SplitCamelCase('-', ""));
        WriteLine("".SplitCamelCase('-', ""));
        WriteLine("pascalCase".SplitCamelCase('-', ""));
    }
    public static string SplitCamelCase(this string text, char separator = '-', string separators = "-=_+!@#$%&*()'^~[]{}/?;:.,<>|\\\"") {
        if (string.IsNullOrEmpty(text) || text.Length < 2) return text;
        var sb = new StringBuilder(text.Length + text.Length / 3);
        for (var i = 0; i < text.Length; i++) {
            if (char.IsUpper(text[i]) && i > 0 && !separators.Contains(text[i - 1].ToString())) sb.Append(separator);
            sb.Append(text[i]);
            
        }
        return sb.ToString();
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

It doesn’t matter if the origin of the string comes from a enum, you do in the text, not in the enum. And take the string of enum has already demonstrated how to make.

  • Kkkkk, I loved the use of extension, exactly what I wanted. I had a little difficulty with extensions, but after this example, I could understand the use, beautiful answer. I just didn’t understand what the string separators makes, in case it checks if the previous character is one of the separators? And if it is not add again?

  • 1

    Exactly that, of course it is optional as shown, and can tell which characters will be considered separators not to repeat. I don’t know if all options result in what I wanted, but then just adapt the criteria. For example, "CC" may be that I prefer not to have a separator

15

I made it based in this answer, she does not use regular expression see:

string camelCase = string.Concat(ExampleEnum.CamelCase.ToString().Select((x,i) => i > 0 && char.IsUpper(x) ? "-" + x.ToString() : x.ToString())); 

Exit:

Camel-Case

See working on .NET Fiddle.

  • I liked the answer too. And sometimes I am tempted to commands only one line kkkk, I accepted the @Maniero because it used extensions and also has the issue of flexibility, I thought it served me better, in addition to the "more performative", even though micro kkkkk that catches my attention also kkkkk =P. Even so, thank you very much for the answer :D

9

I made the following code, it is not as simple as @gato, but it can be more didactic. I hope it helps:

public static void Main()
{
    string camelCase = "CamelCase";
    string newCamelCase= HiffenCamelCase(camelCase);
         
    
    Console.WriteLine(camelCase);
    Console.WriteLine(newCamelCase);
    
}

static string HiffenCamelCase(string s)
{
    if (!String.IsNullOrEmpty(s))
    {
        string result = s[0].ToString();
        for (int i = 1; i < s.Length;i++)
        {
            result += s[i]+ (i+1<s.Length ? (Char.IsUpper(s[i+1]) ?"-" : "") : "");
        }
    
        return result;
    }
    else return s;
}

Exit:

Camelcase

Camel-Case

I put in the . Netfiddle: https://dotnetfiddle.net/kpGVQE

8

Using regular expressions we can for example:

using System.Text.RegularExpressions;
...
id = Regex.Replace(id,"(?<=[a-z])(?=[A-Z])","-");

A complete example could be:

using static System.Console;
using System.Text.RegularExpressions;

public static class Program {
  public static void Main() {
    WriteLine("CamelCase".SplitCamelCase());  }
  public static string SplitCamelCase(this string id){
    return Regex.Replace(id,"(?<=[a-z])(?=[A-Z])","-"); }
}

Naturally, it adapts the expressions to the intended semantics. For example if we want capital sequences to be separated, ..."(?<=[A-Za-z])(?=[A-Z])"...

3

It can be like that too:

string camelCaseString = "EuSouUmaStringCamelCase";
string retorno = System.Text.RegularExpressions.Regex.Replace(
    camelCaseString,
    "(?<=[a-z])([A-Z])",
    "-$1",
    System.Text.RegularExpressions.RegexOptions.Compiled).Trim();

Console.Write(retorno);

Browser other questions tagged

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