gpt4 book ai didi

.net - ToPascalCase() C# for all caps 缩写

转载 作者:行者123 更新时间:2023-12-05 00:25:52 30 4
gpt4 key购买 nike

我正在使用 ReSharper 并试图遵守它的默认规则。

在我的部分代码中,我需要将字符串属性更改为 PascalCase。

我尝试了多种方法,但找不到一种适用于所有大写缩写的方法。

前任:

MPSUser --> Still MPSUser (should be MpsUser)
ArticleID --> Still Article ID (Should be ArticleId)
closeMethod --> Works and changes to CloseMethod

谁能帮我创建一个可以将任何字符串转换为 PascalCase 的方法?
谢谢!

最佳答案

我所知道的用于转换为 PascalCase 的唯一内置方法是 TextInfo.ToTitleCase ,并且它在设计上不处理全大写的单词。为了解决这个问题,我制作了一个自定义正则表达式,可以检测所有单词部分,然后将它们单独转换为 Title/Pascal Case:

string ToPascalCase(string s)
{
// Find word parts using the following rules:
// 1. all lowercase starting at the beginning is a word
// 2. all caps is a word.
// 3. first letter caps, followed by all lowercase is a word
// 4. the entire string must decompose into words according to 1,2,3.
// Note that 2&3 together ensure MPSUser is parsed as "MPS" + "User".

var m = Regex.Match(s, "^(?<word>^[a-z]+|[A-Z]+|[A-Z][a-z]+)+$");
var g = m.Groups["word"];

// Take each word and convert individually to TitleCase
// to generate the final output. Note the use of ToLower
// before ToTitleCase because all caps is treated as an abbreviation.
var t = Thread.CurrentThread.CurrentCulture.TextInfo;
var sb = new StringBuilder();
foreach (var c in g.Captures.Cast<Capture>())
sb.Append(t.ToTitleCase(c.Value.ToLower()));
return sb.ToString();
}

此函数应处理常见用例:
s           | ToPascalCase(s)
MPSUser | MpsUser
ArticleID | ArticleId
closeMethod | CloseMethod

关于.net - ToPascalCase() C# for all caps 缩写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23345348/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com