6

I would like to take a pascal-cased string like "CountOfWidgets" and convert it into something more user-friendly like "Count of Widgets" in C#. Multiple adjacent uppercase characters should be left intact. What is the most efficient way to do this?

NOTE: Duplicate of .NET - How can you split a "caps" delimited string into an array?

Community
  • 1
  • 1
JoshL
  • 10,737
  • 11
  • 55
  • 61
  • This is not a duplicate question because the answer linked to does not cater for "Multiple adjacent uppercase character should be left intact" – PandaWood Mar 29 '17 at 00:53

1 Answers1

16

Don't know about efficient but at least it's terse:

Regex r = new Regex("([A-Z]+[a-z]+)");
string result = r.Replace("CountOfWidgets", m => (m.Value.Length > 3 ? m.Value : m.Value.ToLower()) + " ");
Cristian Libardo
  • 9,260
  • 3
  • 35
  • 41
  • 1
    This leaves a space at the end of "FormatRange" -> "FormatRange " - so a trim would be useful and checking for Length of 3 is a unreliable way of ensuring "multiple adjacent uppercase should be left intact". This just hopes that anything less than 3 characters should be left. So "PubID" goes to "publ ID" which is not right – PandaWood Mar 29 '17 at 00:52