我大量借鑑了mellamokb的解決方案,想出了一些更全面的東西。例如,我想留下數字。另外,我希望將任何非字母,非數字字符用作分隔符。那就是:
public static string ToPascalCase(this string s) {
var result = new StringBuilder();
var nonWordChars = new Regex(@"[^a-zA-Z0-9]+");
var tokens = nonWordChars.Split(s);
foreach (var token in tokens) {
result.Append(PascalCaseSingleWord(token));
}
return result.ToString();
}
static string PascalCaseSingleWord(string s) {
var match = Regex.Match(s, @"^(?<word>\d+|^[a-z]+|[A-Z]+|[A-Z][a-z]+|\d[a-z]+)+$");
var groups = match.Groups["word"];
var textInfo = Thread.CurrentThread.CurrentCulture.TextInfo;
var result = new StringBuilder();
foreach (var capture in groups.Captures.Cast<Capture>()) {
result.Append(textInfo.ToTitleCase(capture.Value.ToLower()));
}
return result.ToString();
}
這裏是X單元測試,顯示一些測試用例:
[Theory]
[InlineData("imAString", "ImAString")]
[InlineData("imAlsoString", "ImAlsoString")]
[InlineData("ImAlsoString", "ImAlsoString")]
[InlineData("im_a_string", "ImAString")]
[InlineData("im a string", "ImAString")]
[InlineData("ABCAcronym", "AbcAcronym")]
[InlineData("im_a_ABCAcronym", "ImAAbcAcronym")]
[InlineData("im a ABCAcronym", "ImAAbcAcronym")]
[InlineData("8ball", "8Ball")]
[InlineData("im a 8ball", "ImA8Ball")]
[InlineData("IM_ALL_CAPS", "ImAllCaps")]
[InlineData("IM ALSO ALL CAPS", "ImAlsoAllCaps")]
[InlineData("i-have-dashes", "IHaveDashes")]
[InlineData("a8word_another_word", "A8WordAnotherWord")]
public void WhenGivenString_ShouldPascalCaseIt(string input, string expectedResult) {
var result = input.ToPascalCase();
Assert.Equal(expectedResult, result);
}
注意,您可以使用ReSharper的註冊縮寫,它將使他們能夠在PascalCased名稱中使用。例如,對於ArticleID,您可以將ID註冊爲縮寫,並且不會再投訴。 –