var input = "MyStringThatIsGreat";
var result = Regex.Replace(input, "(?<!^)([A-Z])", "-$1").ToLower();
Console.WriteLine(result);
或者如果你喜欢循环
var sb = new StringBuilder();
for (var i = 0; i < input.Length; i++)
if (i != 0 && char.IsUpper(input[i]))
sb.Append($"-{input[i]}");
else
sb.Append(input[i]);
Console.WriteLine(sb.ToString().ToLower());
var result = string
.Concat(input
.Select((x, i) => char.IsUpper(x) && i != 0 ? $"-{x}" : x.ToString()))
.ToLower();
输出
my-string-that-is-great
注意
:这两个例子可能都不太了解文化。
Job=.NET Core 5.0 Runtime=.NET Core 5.0
| Method | Mean | Error | StdDev |
|-------------- |---------:|---------:|---------:|
| RegexStandard | 988.6 ns | 19.26 ns | 31.65 ns |
| RegExCompiled | 566.5 ns | 11.08 ns | 16.24 ns |
| StringBuilder | 466.1 ns | 5.54 ns | 4.91 ns |
| Concat | 792.4 ns | 15.09 ns | 16.77 ns |
[SimpleJob(RuntimeMoniker.NetCoreApp50)]
public class DumbTest
{
private string _input = "MyStringThatIsGreat";
private Regex compiled = new Regex("(?<!^)([A-Z])", RegexOptions.Compiled);
[Benchmark]
public string RegexStandard()
=> Regex.Replace(_input, "(?<!^)([A-Z])", "-$1").ToLower();
[Benchmark]
public string RegExCompiled()
=> compiled.Replace(_input, "-$1").ToLower();
[Benchmark]
public string StringBuilder()
{
var sb = new StringBuilder();
for (var i = 0; i < _input.Length; i++)
if (i != 0 && char.IsUpper(_input[i]))
sb.Append($"-{_input[i]}");
else
sb.Append(_input[i]);
return sb.ToString().ToLower();
}
[Benchmark]
public string Concat() =>
string
.Concat(_input.Select((x, i) => char.IsUpper(x) && i != 0 ? $"-{x}" : x.ToString()))
.ToLower();
}