Breaking Away...

June 12, 2007 15:30

Well, the general consensus appears to be that fixing ToProperCase() is the right thing to do, even if it is a breaking change with some short term pain. So, as of Revision 96, the algorithm has been modified. In the interest of getting as many eyes on this as possible, here's the code that performs the transformation. I've set up a number of unit tests for it, but if you see any logical flaws, please let me know:

.
   1:          public static string ToPascalCase(string text, bool removeUnderscores)
   2:          {
   3:              if (String.IsNullOrEmpty(text))
   4:                  return text;
   5:   
   6:              text = text.Replace("_", " ");
   7:              string joinString = removeUnderscores ? String.Empty : "_";
   8:              string[] words = text.Split(' ');
   9:              if (words.Length > 1 || Sugar.Validation.IsUpperCase(words[0]))
  10:              {
  11:                  for (int i = 0; i < words.Length; i++)
  12:                  {
  13:                      if (words[i].Length > 0)
  14:                      {
  15:                          string word = words[i];
  16:                          string restOfWord = word.Substring(1);
  17:   
  18:                          if(Sugar.Validation.IsUpperCase(restOfWord))
  19:                              restOfWord = restOfWord.ToLower(CultureInfo.CurrentUICulture);
  20:   
  21:                          char firstChar = char.ToUpper(word[0], CultureInfo.CurrentUICulture);
  22:                          words[i] = firstChar + restOfWord;
  23:                      }
  24:                  }
  25:                  return String.Join(joinString, words);
  26:              }
  27:              else
  28:              {
  29:                  return words[0].Substring(0, 1).ToUpper(CultureInfo.CurrentUICulture) + words[0].Substring(1);
  30:              }
  31:          }

 

And thanks to Phil for giving me a nice starting point on this!


0 Comments
Actions: E-mail | Permalink | Comment RSSRSS comment feed

Related posts

Comments are closed