Missing ToTitleCase from TextInfo (Silverlight)

by Patrice 5/4/2008 12:35:00 AM

The other day I was converting some "utility" classes to be used within my Silverlight project and I realized (well, the compiler told me) that the ToTitleCase method was missing from System.Globalization.TextInfo. So I created one that ended up being more useful then the original one (well, for my own usage).

The default utility of ToTitleCase is obviously to change the first letter to uppercase and the rest to lowercase (mine can take a complete sentence too). Then a friend of mine gave me a case where it wouldn't work. Take for example "Merriam-Webster"; the W after the dash will be lower case. That's why I added a parameter to my ToTitleCase method, a character list, that are used as "uppercase after this character". The default value is naturally " " (space).

While I was there, I used the new Method Extensions feature.  So it can be used like:

"this sentence to titlecase".ToTitleCase(); 

 

   1:  public static  class UtilsClient
   2:  {
   3:      public static string ToTitleCase(this string value)
   4:      {
   5:          return ToTitleCase(value, new List<char> { ' ' });
   6:      }
   7:   
   8:      public static string ToTitleCase(this string value, List<char> separators)
   9:      {
  10:          string result = "";
  11:          bool nextUpper = true; //first letter always upper case
  12:   
  13:          value = value.ToLower();//initialize all to lower case
  14:   
  15:          for (int charIndex = 0; charIndex < value.Length; charIndex++)
  16:          {
  17:              string nextChar = value[charIndex].ToString();
  18:              if (nextUpper)
  19:              {
  20:                  nextChar = nextChar.ToUpper();
  21:              }
  22:   
  23:              result += nextChar;
  24:   
  25:              if (separators.Any(c => c.Equals(value[charIndex])))//put next char to upper case
  26:                  nextUpper = true;
  27:              else
  28:                  nextUpper = false;
  29:   
  30:          }
  31:   
  32:          return result;
  33:      }
  34:  }

Related posts

Comments

5/5/2008 9:48:35 AM

mike

Exactly what I was looking for. Tks!

mike

Add comment


(Will show your Gravatar icon)  

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

1/6/2009 9:39:59 AM

Powered by BlogEngine.NET 1.3.1.0

LFDX Software Inc.

About the author

P. Lafond Patrice Lafond
(and yes, it's Mr!)
Software Engineer
French Canadian expat in Bermuda for over 7 years.
flag QC  flag BDA

E-mail me Send mail

Calendar

<<  January 2009  >>
MoTuWeThFrSaSu
2930311234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar

Pages

    Recent comments

    Authors

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2009

    Sign in