用连字符字符串替换驼峰字符串

本文关键字:字符串 替换 连字符 | 更新日期: 2023-09-27 17:53:14

如何更改字符串

aboutUs

关于我们

如果可能的话,我希望能够用正则表达式替换做到这一点。我试过了:

public static string ToHypenCase(this string source) {
    return Regex.Replace(source, @"[A-Z]", "-$1");
}

用连字符字符串替换驼峰字符串

您可以使用regex和ToLower()的组合,如下所示:

string s = "quickBrownFoxJumpsOverTheLazyDog";
string res = Regex.Replace(s, @"([a-z])([A-Z])", "$1-$2").ToLower();
Console.WriteLine(res);

如果您需要低分配的快速解决方案(它也处理@PeterL情况):

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);
    }
}
基准:

<表类>文本 错误 StdDev 比例 Gen 0 分配tbody> <<tr> UsingRegex td> 速(…)zyDog [32] 1,894.7 ns2.38 ns2.11 ns1.000.23 ns0.20 ns

你可以这样修改你的扩展方法:

public static string ToHypenCase(this string source)
{
    var chars = source.ToList();
    for (int i = 0; i < chars.Count -1; i++)
    {
        if (!char.IsWhiteSpace(chars[i]) && char.IsUpper(chars[i + 1]))
        {
            chars[i + 1] = char.ToLower(chars[i + 1]);
            chars.Insert(i+1,'-');
        }
    }
    return new string(chars.ToArray());
}

或者直接用LINQ:

var parts = "aboutUs".Select(x =>
        {
            if (char.IsUpper(x)) return "-" + char.ToLower(x);
            return x.ToString();
        });
var result = string.Join("", parts);

我的版本使用StringBuilder…

    public static string UrlConvert(string s)
    {
        if (string.IsNullOrEmpty(s)) return s;
        var sb = new StringBuilder();
        foreach (var ch in s.ToCharArray())
            if (char.IsUpper(ch))
            {
                if (sb.Length > 0) sb.Append("-");
                sb.Append(char.ToLower(ch));
            }
            else
            {
                sb.Append(ch);
            }
        return sb.ToString();
    }

和xUnit测试…

    [Theory]
    [InlineData("same", "same")]
    [InlineData("Simple", "simple")]
    [InlineData("MultiWord", "multi-word")]
    [InlineData("UsingAnAWord", "using-an-a-word")]
    [InlineData("SomeDigit4Used2", "some-digit4-used2")]
    public void UrlConvertWorks(string input, string expected)
    {
        Assert.Equal(expected, Meta.UrlConvert(input));
    }