Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a camel case string with a hyphenated string

Tags:

c#

How would I change the string

aboutUs

To

about-us

I'd like to be able to do this with regex replace if possible. I've tried:

public static string ToHypenCase(this string source) {
    return Regex.Replace(source, @"[A-Z]", "-$1");
}
like image 834
bflemi3 Avatar asked Mar 26 '14 02:03

bflemi3


2 Answers

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.

like image 161
Sergey Kalinichenko Avatar answered Nov 14 '22 18:11

Sergey Kalinichenko


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
like image 27
Pawel Maga Avatar answered Nov 14 '22 16:11

Pawel Maga