Parse Sting: Add space everywhere string goes from capital letter to lowercase letter

I have a web service object that returns an enumertion as it's return message.  The values are strings.  I want a function to add a space everywhere the string goes from a capital letter to a lowercase.  For instance i want this EmailAlreadyRegistered to be Email Already Registered.
davidcahanAsked:
Who is Participating?
 
discon0Connect With a Mentor Commented:
Hello, here's a function that will do what you want.

Examples:
> AddSpacesOnCaps("EmailAlreadyRegistered", true)
"Email Already Registered"

> AddSpacesOnCaps("ThisIsATest", true)
"This Is A Test"

> AddSpacesOnCaps("ThisIsATest", false)
"This Is ATest"



      /// <summary>
      /// Adds a space after lowercase letters when followed by a capital letter.
      /// </summary>
      /// <param name="text">The input text.</param>
      /// <param name="addSpacesOnDoubleCaps">If true it will separate sequential capital letters with spaces as well.</param>
      /// <returns>The new string.</returns>
      public static string AddSpacesOnCaps(string text, bool addSpacesOnDoubleCaps)
      {
            if (text != null)
            {
                  System.Text.StringBuilder sb = new System.Text.StringBuilder();

                  bool prevIsLower = false;
                  for (int i = 0; i < text.Length; i++)
                  {
                        if ((prevIsLower || (addSpacesOnDoubleCaps && i > 0)) && char.IsUpper(text[i]))
                        {
                              sb.Append(" ");
                              prevIsLower = false;
                        }
                        else
                        {
                              if (char.IsLower(text[i]))
                                    prevIsLower = true;
                        }
                        sb.Append(text[i]);
                  }

                  return (sb.ToString());
            }
            else
                  return (null);
      }
0
All Courses

From novice to tech pro — start learning today.