Convert String To Proper Case

by Matt 12. October 2011 15:28

It's a piece of code I wish I didn't use nearly as often I did, but because people like to do data entry with CAPSLOCK on, I feel the need to convert it to Proper Case.

Code Snippet
  1. public static string ProperCase(string stringInput)
  2.         {
  3.             System.Text.StringBuilder sb = new System.Text.StringBuilder();
  4.             bool fEmptyBefore = true;
  5.             foreach (char ch in stringInput)
  6.             {
  7.                 char chThis = ch;
  8.                 if (Char.IsWhiteSpace(chThis))
  9.                     fEmptyBefore = true;
  10.                 else
  11.                 {
  12.                     if (Char.IsLetter(chThis) && fEmptyBefore)
  13.                         chThis = Char.ToUpper(chThis);
  14.                     else
  15.                         chThis = Char.ToLower(chThis);
  16.                     fEmptyBefore = false;
  17.                 }
  18.                 sb.Append(chThis);
  19.             }
  20.             return sb.ToString();
  21.         }

 

It's not perfect - for example, It won't properly display my name, McGuire, if it's converting it from caps.  But how would it know to capitalize the 'G'? 

Tags: , ,
Categories: .NET | C# | Strings