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?– Vinícius Lima
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
– Maniero