Extending the string object in c#
Published on Jan 04, 2008Thanks to Peter I modify where the string[] is declared and changed an obvious mistake instead of string s = “”; I use the correct form of string s = string.Empty;, I can’t believe I miss that one, I really annoy my team with that :-)
I have found some controversy in some post in the wild where I demonstrate how to extend the string object. Sometimes the controversy is around the examples presented. So I decided to make my own example with methods that I wish were included in the framework.
String has two very useful methods ToUpper() and ToLower(), but I found myself looking for a good ToCamel(), ToPascal(), Capitalize() and CapitalizeAll() methods one too many times.
Let’s write down what we want to accomplish.
Method | Definition |
ToCamel() | Given a set of words separated by a space or an underscore return a lower Camel cased word. ex: Hernan Garcia → hernanGarcia |
ToPascal() | Like ToCamel but all words start with an uppercase |
Capitalize() | Given a word or a phrase make the first letter of the phrase and the first letter after a point Upper case and all the rest lower case. |
CapitalizeAll() | Like Capitalize but all words start with an uppercase letter. |
ToCamel()
The implementation is super simple.
An example of usage:
The result:
ToPascal()
Example:
The result:
Capitalize()
The code
Example:
The result:
CapitalizeAll()
The code:
Example:
The result:
There are some other methods in this same line that we can create, for example a method to convert back from Pascal or Camel into a space or underscore separate string.