Saturday, April 19, 2014

Formatting / Splitting string from Title Case to Delimited Words



Let the code speak :-)

namespace tests
{
       [TestClass]
       public class string_extension_tests
       {
              [TestMethod]
              public void when_formatting_title_case_to_delimited_but_the_delimiter_is_not_specified()
              {
                     var s = "ThisIsTheDayThatTheLordHasMade";
                     var formated = s.TitleCaseToDelimited();
                     const string expected = "This Is The Day That The Lord Has Made";
                     Assert.AreEqual(expected, formated);
              }

              [TestMethod]
              public void when_formatting_title_case_to_delimited_and_the_delimiter_is_specified()
              {
                     var s = "ThisIsTheDayThatTheLordHasMade";
                     var formated = s.TitleCaseToDelimited("_");
                     const string expected = "This_Is_The_Day_That_The_Lord_Has_Made";
                     Assert.AreEqual(expected, formated);
              }

       }

       ///

       /// String helpers
       ///

       public static class StringExtensions
       {
              ///

              /// It converts a string with the format of "ThisIsTheDayThatTheLordHasMade" to "This Is The Day The Lord Has Made"
              /// insprired by the conversation here: http://stackoverflow.com/questions/155303/net-how-can-you-split-a-caps-delimited-string-into-an-array
              /// Limitation: this will split all upper cased letters into separate words.  I don't have a need to for consecutive upper
        /// case words to be as one word so go YAGNI.
              ///

              ///
              ///
              ///
              public static string TitleCaseToDelimited(this string str, params string[] delimiters)
              {
                     //if there is no data, let's waste our breath
                     if (string.IsNullOrWhiteSpace(str)) return str;
                     //if no delimiter specified, use space
                     string delimiter;
                     if (delimiters.Length == 0 || string.IsNullOrWhiteSpace(delimiters[0])) delimiter = " ";
                     else delimiter = delimiters[0];
                     //regex does the magic
                     return Regex.Replace(str, "(\\B[A-Z])", delimiter + "$1");
              }
       }
}

About Cullen

My photo
Christian, Father, Software Developer/Architect who enjoys technology and using it to make people's lives easier!

Followers