Replace a camel case string with a hyphenated string
You can do it with a combination of regex and ToLower()
, like this:
string s = "quickBrownFoxJumpsOverTheLazyDog";
string res = Regex.Replace(s, @"([a-z])([A-Z])", "$1-$2").ToLower();
Console.WriteLine(res);
Demo on ideone.
If you need fast solution with low allocation (it handles also @PeterL cases):
public static string ConvertFromCamelCaseToDashSyntax(string text)
{
var buffer = ArrayPool<char>.Shared.Rent(text.Length + 10); // define max size of the internal buffer, 10 = max 10 segments
try
{
var resultLength = 0;
for (var i = 0; i < text.Length; i++)
{
if (char.IsUpper(text[i]) && i > 0)
{
buffer[resultLength++] = '-';
}
buffer[resultLength++] = char.ToLowerInvariant(text[i]);
}
return new string(buffer.AsSpan().Slice(0, resultLength));
}
finally
{
ArrayPool<char>.Shared.Return(buffer);
}
}
Benchmark:
Method | Text | Mean | Error | StdDev | Ratio | Gen 0 | Allocated |
---|---|---|---|---|---|---|---|
UsingRegex | quick(...)zyDog [32] | 1,894.7 ns | 2.38 ns | 2.11 ns | 1.00 | 0.0114 | 208 B |
UsingArrayPoolAndSpans | quick(...)zyDog [32] | 106.3 ns | 0.23 ns | 0.20 ns | 0.06 | 0.0062 | 104 B |