The only built-in method I know of for converting to PascalCase
is TextInfo.ToTitleCase
, and it doesn't handle all-caps words by design. To work around this, I have crafted a custom regular expression that can detect all the word parts, and then they are individually converted to 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();
}
This function should handle the common use cases:
s | ToPascalCase(s)
MPSUser | MpsUser
ArticleID | ArticleId
closeMethod | CloseMethod